π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): accept device=None in OnnxLightGlue (#5859)
Muhammad Talha5c2cd5e0dd56
diff --git a/changelog.d/5859.fixed.md b/changelog.d/5859.fixed.mdnew file mode 100644index 000000000..eed1e42dc--- /dev/null+++ b/changelog.d/5859.fixed.md@@ -0,0 +1,2 @@+`OnnxLightGlue(device=None)` no longer raises torch's `TypeError` from `torch.device(None)`. `None` is now+treated as `"cpu"`, as in the other kornia feature constructors, and the `device` docstring says so.diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.pyindex c585faa27..9ae0a4b71 100644--- a/kornia/feature/lightglue_onnx/lightglue.py+++ b/kornia/feature/lightglue_onnx/lightglue.py@@ -52,14 +52,13 @@ class OnnxLightGlue:with ``image_size`` in the order ``(W, H)``, and the same range check applies. Unlike:class:`~kornia.feature.LightGlue`, it takes float32 inputs with a batch of one and no scales, orientationsor LAFs, and it runs on CPU or CUDA only.- - Known defects: ``device=None`` raises a ``TypeError``, although the signature allows ``None``- (`#5850 <https://github.com/kornia/kornia/issues/5850>`_).Args:weights: Pretrained weights, or a path to your own exported ONNX model. Available pretrained weightsare ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``. `Note that FP16 requires CUDA.`Defaults to ``'disk_fp16'`` if ``device`` is CUDA, and ``'disk'`` if CPU.- device: ``'cpu'`` or ``'cuda'`` to run inference on; another device raises ``ValueError``.+ device: ``'cpu'`` or ``'cuda'`` to run inference on; another device raises ``ValueError``. ``None`` means+ ``'cpu'``, as in the other kornia feature constructors, not torch's current default device."""@@ -79,7 +78,7 @@ class OnnxLightGlue:_ = _ort.__version__KORNIA_CHECK(importlib.util.find_spec("numpy") is not None, "numpy is not installed.")- device = torch.device(device) # type: ignore+ device = torch.device("cpu") if device is None else torch.device(device)self.device = deviceif device.type == "cpu":diff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.pyindex 552bed3ba..1576a7edd 100644--- a/tests/feature/test_lightglue_onnx.py+++ b/tests/feature/test_lightglue_onnx.py@@ -74,35 +74,40 @@ def test_missing_onnxruntime_applies_the_installation_mode(monkeypatch, without_assert commands == [[sys.executable, "-m", "pip", "install", "kornia[onnx]"]]+def _write_local_model(tmp_path):+ """Write a tiny local graph that stands in for a LightGlue model, so no pretrained weights are downloaded."""+ from onnx import TensorProto, helper, save++ # It exercises session creation and all four NumPy-typed input bindings without requiring CUDA.+ inputs = [+ helper.make_tensor_value_info(name, TensorProto.FLOAT, [1, 2, width])+ for name, width in [("kpts0", 2), ("kpts1", 2), ("desc0", 4), ("desc1", 4)]+ ]+ outputs = [+ helper.make_tensor_value_info("matches0", TensorProto.INT64, [1, 2]),+ helper.make_tensor_value_info("mscores0", TensorProto.FLOAT, [1]),+ ]+ nodes = [+ helper.make_node(+ "Constant", [], ["matches0"], value=helper.make_tensor("matches", TensorProto.INT64, [1, 2], [0, 1])+ ),+ helper.make_node(+ "Constant", [], ["mscores0"], value=helper.make_tensor("scores", TensorProto.FLOAT, [1], [0.75])+ ),+ ]+ graph = helper.make_graph(nodes, "lightglue_alias_smoke", inputs, outputs)+ model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)], ir_version=8)+ path = tmp_path / "lightglue.onnx"+ save(model, path)+ return path++@pytest.mark.skipif(ort is None, reason="OnnxLightGlue requires onnxruntime-gpu")@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Needs dlpack")class TestOnnxLightGlue:@pytest.mark.device_agnosticdef test_local_model_inference(self, tmp_path):- from onnx import TensorProto, helper, save-- # A tiny local graph exercises session creation and all four NumPy-typed input- # bindings without downloading pretrained weights or requiring CUDA.- inputs = [- helper.make_tensor_value_info(name, TensorProto.FLOAT, [1, 2, width])- for name, width in [("kpts0", 2), ("kpts1", 2), ("desc0", 4), ("desc1", 4)]- ]- outputs = [- helper.make_tensor_value_info("matches0", TensorProto.INT64, [1, 2]),- helper.make_tensor_value_info("mscores0", TensorProto.FLOAT, [1]),- ]- nodes = [- helper.make_node(- "Constant", [], ["matches0"], value=helper.make_tensor("matches", TensorProto.INT64, [1, 2], [0, 1])- ),- helper.make_node(- "Constant", [], ["mscores0"], value=helper.make_tensor("scores", TensorProto.FLOAT, [1], [0.75])- ),- ]- graph = helper.make_graph(nodes, "lightglue_alias_smoke", inputs, outputs)- model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)], ir_version=8)- path = tmp_path / "lightglue.onnx"- save(model, path)+ path = _write_local_model(tmp_path)matcher = OnnxLightGlue(str(path), device="cpu")features = {@@ -114,6 +119,34 @@ class TestOnnxLightGlue:torch.testing.assert_close(result["matches"], torch.tensor([[0, 1]]))torch.testing.assert_close(result["scores"], torch.tensor([0.75]))+ @pytest.mark.device_agnostic+ def test_device_none_means_cpu(self, monkeypatch, tmp_path):+ # The signature allows ``device=None``, which means CPU.+ path = _write_local_model(tmp_path)+ urls = []++ def fake_download(url):+ urls.append(url)+ return str(path)++ monkeypatch.setattr("kornia.feature.lightglue_onnx.lightglue.download_onnx_from_url", fake_download)++ # ``None`` means CPU, not torch's current default device.+ with torch.device("meta"):+ matcher = OnnxLightGlue(device=None)+ assert matcher.device == torch.device("cpu")+ # ``weights=None`` resolves from the device: the CPU build of ``disk``, as for ``device="cpu"``.+ assert urls == [OnnxLightGlue.MODEL_URLS["disk"].replace(".onnx", "_cpu.onnx")]++ features = {+ "keypoints": torch.tensor([[[0.0, 0.0], [5.0, 5.0]]]),+ "descriptors": torch.ones(1, 2, 4),+ "image_size": torch.tensor([[10, 10]]),+ }+ result = matcher({"image0": features, "image1": features})+ assert result["matches"].device.type == "cpu"+ torch.testing.assert_close(result["matches"], torch.tensor([[0, 1]]))+@pytest.mark.slow@pytest.mark.skipif(not torch.cuda.is_available(), reason="Test requires CUDA")@pytest.mark.parametrize("weights", ["disk", "superpoint", "disk_fp16", "superpoint_fp16"])