Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: CPU support for OnnxLightGlue (#2643)

Fabio M. Sim865de5d62ea0
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 1bfa76381..cf4913a38 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -30,8 +30,9 @@ class OnnxLightGlue:
Args:
weights: Pretrained weights, or a path to your own exported ONNX model. Available pretrained weights
- are ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``.
- device: Device to run inference on. Currently, only ``'cuda'`` is supported. Defaults to ``'cuda'``.
+ are ``'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: Device to run inference on.
"""
MODEL_URLS: ClassVar[dict[str, str]] = {
@@ -43,25 +44,32 @@ class OnnxLightGlue:
required_data_keys: ClassVar[list[str]] = ["image0", "image1"]
- def __init__(self, weights: str = "disk_fp16", device: Device = None) -> None:
+ def __init__(self, weights: str | None = None, device: Device = "cpu") -> None:
KORNIA_CHECK(ort is not None, "onnxruntime is not installed.")
KORNIA_CHECK(np is not None, "numpy is not installed.")
- if device is None:
- device = torch.device("cuda")
- elif isinstance(device, str):
- device = torch.device(device)
+ device = torch.device(device) # type: ignore
self.device = device
if device.type == "cpu":
- raise NotImplementedError("CPUExecutionProvider is not supported yet for Multihead-Attention op.")
+ providers = ["CPUExecutionProvider"]
elif device.type == "cuda":
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
else:
raise ValueError(f"Unsupported device {device}")
+ if weights is None:
+ weights = "disk_fp16" if device.type == "cuda" else "disk"
+
if weights in self.MODEL_URLS:
- weights = download_onnx_from_url(self.MODEL_URLS[weights])
+ if "fp16" in weights:
+ KORNIA_CHECK(device.type == "cuda", "FP16 requires CUDA.")
+
+ url = self.MODEL_URLS[weights]
+ if device.type == "cpu":
+ url = url.replace(".onnx", "_cpu.onnx")
+
+ weights = download_onnx_from_url(url)
self.session = ort.InferenceSession(weights, providers=providers)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 9641a9ec9..70be73e8b 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -112,10 +112,10 @@ def depth_to_3d_v2(
@deprecated(
replace_with="depth_to_3d_v2",
- version='0.7.0',
+ version="0.7.0",
extra_reason=(
- ' This function will be replaced with the `depth_to_3d_v2` behaviour, where the that does not require the'
- ' creation of a meshgrid. The return shape can be not backward compatible between these implementations.'
+ " This function will be replaced with the `depth_to_3d_v2` behaviour, where the that does not require the"
+ " creation of a meshgrid. The return shape can be not backward compatible between these implementations."
),
)
def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:
diff --git a/test/feature/test_lightglue_onnx.py b/test/feature/test_lightglue_onnx.py
index b0b12e894..ace6fc609 100644
--- a/test/feature/test_lightglue_onnx.py
+++ b/test/feature/test_lightglue_onnx.py
@@ -11,22 +11,28 @@ except ImportError:
@pytest.mark.skipif(ort is None, reason="OnnxLightGlue requires onnxruntime-gpu")
[email protected](not torch.cuda.is_available(), reason="OnnxLightGlue requires CUDA")
class TestOnnxLightGlue:
@pytest.mark.slow
- @pytest.mark.parametrize("weights", OnnxLightGlue.MODEL_URLS.keys())
- def test_pretrained_weights(self, weights):
- model = OnnxLightGlue(weights)
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="Test requires CUDA")
+ @pytest.mark.parametrize("weights", ["disk", "superpoint", "disk_fp16", "superpoint_fp16"])
+ def test_pretrained_weights_cuda(self, weights):
+ model = OnnxLightGlue(weights, "cuda")
assert model is not None
@pytest.mark.slow
- def test_forward(self):
- model = OnnxLightGlue()
+ @pytest.mark.parametrize("weights", ["disk", "superpoint"])
+ def test_pretrained_weights_cpu(self, weights):
+ model = OnnxLightGlue(weights, "cpu")
+ assert model is not None
- device = torch.device("cuda")
- kpts = torch.zeros(1, 5, 2, device=device)
- desc = torch.zeros(1, 5, 128, device=device)
- image = torch.zeros(1, 3, 10, 10)
+ @pytest.mark.slow
+ @pytest.mark.parametrize("dtype", [torch.float32])
+ def test_forward(self, dtype, device):
+ model = OnnxLightGlue(device=device)
+
+ kpts = torch.zeros(1, 5, 2, dtype=dtype, device=device)
+ desc = torch.zeros(1, 5, 128, dtype=dtype, device=device)
+ image = torch.zeros(1, 3, 10, 10, dtype=dtype)
outputs = model(
{
"image0": {"keypoints": kpts, "descriptors": desc, "image": image},
@@ -44,14 +50,18 @@ class TestOnnxLightGlue:
assert torch.all(torch.abs(kpts) <= 1).item()
@pytest.mark.slow
- def test_exception(self):
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="Test requires CUDA")
+ def test_exception(self, device):
with pytest.raises(RuntimeError) as e:
OnnxLightGlue(device="invalid device")
assert "Invalid device string: 'invalid device'" in str(e)
- model = OnnxLightGlue()
+ with pytest.raises(Exception) as e:
+ OnnxLightGlue("disk_fp16", "cpu")
+ assert "FP16 requires CUDA." in str(e)
+
+ model = OnnxLightGlue(device=device)
- device = torch.device("cuda")
kpts = torch.zeros(1, 5, 2, device=device)
desc = torch.zeros(1, 5, 128, device=device)
image = torch.zeros(1, 3, 10, 10)
@@ -76,10 +86,15 @@ class TestOnnxLightGlue:
assert "Wrong dtype" in str(e)
# Wrong device
+ wrong_device = torch.device("cpu" if device.type == "cuda" else "cuda")
with pytest.raises(Exception) as e:
model(
{
- "image0": {"keypoints": torch.zeros(1, 5, 2, device="cpu"), "descriptors": desc, "image": image},
+ "image0": {
+ "keypoints": torch.zeros(1, 5, 2, device=wrong_device),
+ "descriptors": desc,
+ "image": image,
+ },
"image1": {"keypoints": kpts, "descriptors": desc, "image": image},
}
)