π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix BoxFiltering class-list device mismatch in forward (#6184)
Muhammad Talhadb1e927b5365
diff --git a/changelog.d/6184.fixed.md b/changelog.d/6184.fixed.mdnew file mode 100644index 000000000..6d0285761--- /dev/null+++ b/changelog.d/6184.fixed.md@@ -0,0 +1 @@+`BoxFiltering` with `classes_to_keep` now runs on boxes on another device than the class list, such as after `.to(device)` or `.cuda()`, instead of raising `RuntimeError: Expected all tensors to be on the same device`: `forward` moves the class list to the boxes' device, also one passed to `forward`. A `confidence_threshold` tensor of more than one element no longer raises `RuntimeError: Boolean value of Tensor with more than one value is ambiguous` in the constructor.diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex 69fabfa45..277621cb2 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -389,18 +389,8 @@ class BoxFiltering(nn.Module, ONNXExportMixin):) -> None:super().__init__()self.filter_as_zero = filter_as_zero- self.classes_to_keep = None- self.confidence_threshold = None- if classes_to_keep is not None:- self.classes_to_keep = (- classes_to_keep if isinstance(classes_to_keep, torch.Tensor) else torch.tensor(classes_to_keep)- )- if confidence_threshold is not None:- self.confidence_threshold = (- confidence_threshold or confidence_threshold- if isinstance(confidence_threshold, torch.Tensor)- else torch.tensor(confidence_threshold)- )+ self.classes_to_keep = None if classes_to_keep is None else torch.as_tensor(classes_to_keep)+ self.confidence_threshold = None if confidence_threshold is None else torch.as_tensor(confidence_threshold)def forward(self,@@ -439,7 +429,9 @@ class BoxFiltering(nn.Module, ONNXExportMixin):classes_to_keep = self.classes_to_keepif classes_to_keep is not None:class_ids = boxes[:, :, 0:1] # [B, D, 1]- classes_to_keep = classes_to_keep.view(1, 1, -1) # [1, 1, C] for broadcasting+ # `.to(device)` leaves the class list on the device it was built on, so follow the boxes. The 0-d+ # threshold needs no move: a 0-d CPU tensor works next to boxes on any device.+ classes_to_keep = classes_to_keep.to(boxes.device).view(1, 1, -1) # [1, 1, C] for broadcastingclass_mask = (class_ids == classes_to_keep).any(dim=-1) # [B, D]else:# If no class filtering is needed, just use a mask of all `True`diff --git a/tests/models/test_box_filtering.py b/tests/models/test_box_filtering.pyindex 809a2894b..903dbb217 100644--- a/tests/models/test_box_filtering.py+++ b/tests/models/test_box_filtering.py@@ -21,6 +21,8 @@ from numpy.testing import assert_almost_equalfrom kornia.contrib.object_detection import BoxFiltering+from testing.base import BaseTester+class TestBoxFiltering:@pytest.fixture@@ -114,3 +116,76 @@ class TestBoxFiltering:assert len(filtered_boxes[0]) == 4 # All boxes in the first batch should be keptassert len(filtered_boxes[1]) == 4 # All boxes in the second batch should be keptassert len(filtered_boxes[2]) == 4 # All boxes in the third batch should be kept+++class TestBoxFilteringDevice(BaseTester):+ """The filter runs on the boxes' device after ``.to(device)``, and what worked before keeps working (#6180)."""++ @staticmethod+ def _boxes(device, dtype):+ # (class_id, confidence, x, y, w, h): classes cycle through 0..4, confidences span (0, 1).+ generator = torch.Generator().manual_seed(0)+ boxes = torch.rand(2, 20, 6, generator=generator)+ boxes[..., 0] = torch.arange(20) % 5+ return boxes.to(device=device, dtype=dtype)++ @pytest.mark.parametrize("kwargs", [{"classes_to_keep": [0, 1, 2]}, {"confidence_threshold": 0.5}])+ def test_runs_next_to_meta_boxes_6180(self, kwargs):+ """The ``meta`` device stands in for CUDA: a class list left on the CPU raised, as next to CUDA boxes."""+ module = BoxFiltering(filter_as_zero=True, **kwargs).to("meta")+ out = module(torch.rand(2, 20, 6, device="meta"))+ assert out.device.type == "meta"+ assert out.shape == (2, 20, 6)++ @pytest.mark.parametrize("filter_as_zero", [False, True])+ def test_matches_cpu_after_moving_the_module_6180(self, device, dtype, filter_as_zero):+ """With the CUDA fixture this is the issue's scenario: it raised before the class list followed the boxes."""+ kwargs = {"confidence_threshold": 0.5, "classes_to_keep": [0, 1, 2], "filter_as_zero": filter_as_zero}+ expected = BoxFiltering(**kwargs)(self._boxes("cpu", dtype))+ actual = BoxFiltering(**kwargs).to(device)(self._boxes(device, dtype))++ if filter_as_zero:+ # A comparison that kept or dropped every box would pass for the wrong reason.+ assert 0 < (expected[..., 1] != 0).sum() < expected.shape[0] * expected.shape[1]+ assert actual.device.type == device.type+ self.assert_close(actual.cpu(), expected)+ else:+ assert 0 < sum(len(e) for e in expected) < 2 * 20+ assert len(actual) == len(expected)+ for got, want in zip(actual, expected):+ assert got.device.type == device.type+ self.assert_close(got.cpu(), want)++ def test_classes_passed_to_forward_follow_the_boxes_6180(self, device, dtype):+ boxes = self._boxes(device, dtype)+ out = BoxFiltering(0.5, filter_as_zero=True)(boxes, None, torch.tensor([0, 1, 2]))+ keep = (boxes[..., 1] > 0.5) & (boxes[..., 0] < 3)+ self.assert_close(out, boxes * keep[..., None])++ @pytest.mark.parametrize("value", [0.5, 0, torch.tensor(0.5), torch.tensor(0.5, dtype=torch.float64), None])+ def test_threshold_assigned_after_construction_6180(self, device, dtype, value):+ """A Python number assigned to the threshold keeps working, also after ``.to(device)``.++ A 0-d CPU threshold works next to boxes on any device, a float64 one also on MPS, which holds no float64.+ """+ boxes = self._boxes(device, dtype)+ module = BoxFiltering(0.9, classes_to_keep=[0, 1, 2], filter_as_zero=True).to(device)+ module.confidence_threshold = value+ threshold = 0.0 if value is None else float(value)+ keep = (boxes[..., 1] > threshold) & (boxes[..., 0] < 3)+ assert 0 < keep.sum() < keep.numel()+ self.assert_close(module(boxes), boxes * keep[..., None])++ def test_half_module_keeps_the_threshold_6180(self):+ """``.half()`` leaves the threshold alone: 0.3 is 0.30004883 in float16, which would drop this box."""+ boxes = self._boxes("cpu", torch.float32)+ boxes[0, 0, 1] = 0.30002+ expected = BoxFiltering(0.3, filter_as_zero=True)(boxes)+ assert expected[0, 0, 1] == boxes[0, 0, 1]+ self.assert_close(BoxFiltering(0.3, filter_as_zero=True).half()(boxes), expected, rtol=0, atol=0)++ @pytest.mark.parametrize("kwargs", [{}, {"confidence_threshold": 0.5, "classes_to_keep": [0, 1, 2]}])+ def test_jit_6180(self, device, dtype, kwargs):+ module = BoxFiltering(filter_as_zero=True, **kwargs).to(device)+ boxes = self._boxes(device, dtype)+ self.assert_close(torch.jit.script(module)(boxes), module(boxes))