Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: LightGlue-ONNX (#2631)

Fabio M. Sim6d3ed9ac74f8
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 2ae561429..e112fa36f 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -112,6 +112,9 @@ Matching
.. autoclass:: LoFTR
:members: forward
+.. autoclass:: OnnxLightGlue
+ :members: forward
+
Local Affine Frames (LAF)
-------------------------
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index ed4a5e057..1748da400 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -39,6 +39,7 @@ from .laf import (
set_laf_orientation,
)
from .lightglue import LightGlue
+from .lightglue_onnx import OnnxLightGlue
from .loftr import LoFTR
from .matching import (
DescriptorMatcher,
@@ -159,4 +160,5 @@ __all__ = [
"DISKFeatures",
"LightGlue",
"LightGlueMatcher",
+ "OnnxLightGlue",
]
diff --git a/kornia/feature/lightglue_onnx/__init__.py b/kornia/feature/lightglue_onnx/__init__.py
new file mode 100644
index 000000000..a5992776d
--- /dev/null
+++ b/kornia/feature/lightglue_onnx/__init__.py
@@ -0,0 +1 @@
+from .lightglue import OnnxLightGlue
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
new file mode 100644
index 000000000..347e74abd
--- /dev/null
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -0,0 +1,154 @@
+from __future__ import annotations
+
+from typing import ClassVar
+
+import torch
+
+from kornia.core import Device, Tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE
+
+from .utils import download_onnx_from_url, normalize_keypoints
+
+try:
+ import numpy as np
+ import onnxruntime as ort
+except ImportError:
+ np = None # type: ignore
+ ort = None
+
+__all__ = ["OnnxLightGlue"]
+
+
+class OnnxLightGlue:
+ r"""Wrapper for loading LightGlue-ONNX models and running inference via ONNXRuntime.
+
+ LightGlue :cite:`LightGlue2023` performs fast descriptor-based deep keypoint matching.
+ This module requires `onnxruntime` to be installed.
+
+ If you have trained your own LightGlue model, see https://github.com/fabio-sim/LightGlue-ONNX
+ for how to export the model to ONNX and optimize it.
+
+ Args:
+ weights: Pretrained weights, or a path to your own exported ONNX model. Available pretrained weights are:
+ `disk`, `superpoint`, `disk_fp16`, and `superpoint_fp16`. Defaults to `disk_fp16`.
+ device: Device to run inference on. Currently, only `cuda` is supported. Defaults to `cuda`.
+ """
+ MODEL_URLS: ClassVar[dict[str, str]] = {
+ "disk": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused.onnx",
+ "superpoint": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/superpoint_lightglue_fused.onnx",
+ "disk_fp16": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused_fp16.onnx",
+ "superpoint_fp16": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/superpoint_lightglue_fused_fp16.onnx",
+ }
+
+ required_data_keys: ClassVar[list[str]] = ["image0", "image1"]
+
+ def __init__(self, weights: str = "disk_fp16", device: Device = None) -> 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)
+ self.device = device
+
+ if device.type == "cpu":
+ raise NotImplementedError("CPUExecutionProvider is not supported yet for Multihead-Attention op.")
+ elif device.type == "cuda":
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
+ else:
+ raise ValueError(f"Unsupported device {device}")
+
+ if weights in self.MODEL_URLS:
+ weights = download_onnx_from_url(self.MODEL_URLS[weights])
+
+ self.session = ort.InferenceSession(weights, providers=providers)
+
+ def __call__(self, data: dict[str, dict[str, Tensor]]) -> dict[str, Tensor]:
+ return self.forward(data)
+
+ def forward(self, data: dict[str, dict[str, Tensor]]) -> dict[str, Tensor]:
+ r"""Match keypoints and descriptors between two images.
+
+ The output contains the matches (the indices of the matching keypoint pairs between the first and second image)
+ and the corresponding confidence scores.
+ Only a batch size of 1 is supported.
+
+ Args:
+ data: Dictionary containing both images and the keypoints and descriptors thereof.
+
+ Returns:
+ output: Dictionary containing the following matches and scores.
+
+ `data`:
+ image0: dict
+ keypoints (`float32`): [1 x M x 2]
+ descriptors (`float32`): [1 x M x D]
+ image: [1 x C x H x W] or image_size: [1 x 2]
+ image1: dict
+ keypoints (`float32`): [1 x N x 2]
+ descriptors (`float32`): [1 x N x D]
+ image: [1 x C x H x W] or image_size: [1 x 2]
+
+ `output`:
+ matches (`int64`): [S x 2]
+ scores (`float32`): [S]
+ """
+ # Input validation.
+ for key in self.required_data_keys:
+ KORNIA_CHECK(key in data, f'Missing key {key} in data')
+ data0, data1 = data['image0'], data['image1']
+ kpts0_, kpts1_ = data0['keypoints'].contiguous(), data1['keypoints'].contiguous()
+ desc0, desc1 = data0['descriptors'].contiguous(), data1['descriptors'].contiguous()
+ KORNIA_CHECK_SAME_DEVICES([kpts0_, desc0, kpts1_, desc1], "Wrong device")
+ KORNIA_CHECK(kpts0_.device.type == self.device.type, "Wrong device")
+ KORNIA_CHECK(torch.float32 == kpts0_.dtype == kpts1_.dtype == desc0.dtype == desc1.dtype, "Wrong dtype")
+ KORNIA_CHECK_SHAPE(kpts0_, ["1", "M", "2"])
+ KORNIA_CHECK_SHAPE(kpts1_, ["1", "N", "2"])
+ KORNIA_CHECK_SHAPE(desc0, ["1", "M", "D"])
+ KORNIA_CHECK_SHAPE(desc1, ["1", "N", "D"])
+ KORNIA_CHECK(kpts0_.shape[1] == desc0.shape[1], "Number of keypoints does not match number of descriptors")
+ KORNIA_CHECK(kpts1_.shape[1] == desc1.shape[1], "Number of keypoints does not match number of descriptors")
+ KORNIA_CHECK(desc0.shape[2] == desc1.shape[2], "Descriptors' dimensions do not match")
+
+ # Normalize keypoints.
+ size0, size1 = data0.get('image_size'), data1.get('image_size')
+ size0 = size0 if size0 is not None else data0['image'].shape[-2:][::-1] # type: ignore
+ size1 = size1 if size1 is not None else data1['image'].shape[-2:][::-1] # type: ignore
+
+ kpts0 = normalize_keypoints(kpts0_, size=size0) # type: ignore
+ kpts1 = normalize_keypoints(kpts1_, size=size1) # type: ignore
+
+ KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore
+ KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore
+
+ # Inference.
+ lightglue_inputs = {"kpts0": kpts0, "kpts1": kpts1, "desc0": desc0, "desc1": desc1}
+ lightglue_outputs = ["matches0", "mscores0"]
+ binding = self.session.io_binding()
+
+ for name, tensor in lightglue_inputs.items():
+ binding.bind_input(
+ name,
+ device_type=self.device.type,
+ device_id=0,
+ element_type=np.float32,
+ shape=tuple(tensor.shape),
+ buffer_ptr=tensor.data_ptr(),
+ )
+
+ for name in lightglue_outputs:
+ binding.bind_output(name, device_type=self.device.type, device_id=0)
+
+ self.session.run_with_iobinding(binding)
+
+ matches, mscores = binding.get_outputs()
+
+ # TODO: The following is an unnecessary copy. Replace with a better solution when torch supports
+ # constructing a tensor from a data pointer, or when ORT supports converting to torch tensor.
+ # https://github.com/microsoft/onnxruntime/issues/15963
+ outputs = {
+ "matches": torch.from_dlpack(matches.numpy()).to(self.device),
+ "scores": torch.from_dlpack(mscores.numpy()).to(self.device),
+ }
+ return outputs
diff --git a/kornia/feature/lightglue_onnx/utils/__init__.py b/kornia/feature/lightglue_onnx/utils/__init__.py
new file mode 100644
index 000000000..02ad11eae
--- /dev/null
+++ b/kornia/feature/lightglue_onnx/utils/__init__.py
@@ -0,0 +1,2 @@
+from .download import download_onnx_from_url
+from .keypoints import normalize_keypoints
diff --git a/kornia/feature/lightglue_onnx/utils/download.py b/kornia/feature/lightglue_onnx/utils/download.py
new file mode 100644
index 000000000..3aaff41f5
--- /dev/null
+++ b/kornia/feature/lightglue_onnx/utils/download.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+import os
+import sys
+from typing import Optional
+from urllib.parse import urlparse
+
+from torch.hub import HASH_REGEX, download_url_to_file, get_dir
+
+
+def download_onnx_from_url(
+ url: str,
+ model_dir: Optional[str] = None,
+ progress: bool = True,
+ check_hash: bool = False,
+ file_name: Optional[str] = None,
+) -> str:
+ r"""Loads the ONNX model at the given URL.
+
+ If downloaded file is a zip file, it will be automatically
+ decompressed.
+
+ If the object is already present in `model_dir`, it's deserialized and
+ returned.
+ The default value of ``model_dir`` is ``<hub_dir>/checkpoints`` where
+ ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.
+
+ Args:
+ url (str): URL of the object to download
+ model_dir (str, optional): directory in which to save the object
+ progress (bool, optional): whether or not to display a progress bar to stderr.
+ Default: True
+ check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention
+ ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
+ digits of the SHA256 hash of the contents of the file. The hash is used to
+ ensure unique names and to verify the contents of the file.
+ Default: False
+ file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set.
+
+ Example:
+ >>> model = download_onnx_from_url('https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused_fp16.onnx')
+ """
+ if model_dir is None:
+ hub_dir = get_dir()
+ model_dir = os.path.join(hub_dir, 'checkpoints')
+
+ os.makedirs(model_dir, exist_ok=True)
+
+ parts = urlparse(url)
+ filename = os.path.basename(parts.path)
+ if file_name is not None:
+ filename = file_name
+ cached_file = os.path.join(model_dir, filename)
+ if not os.path.exists(cached_file):
+ sys.stderr.write(f'Downloading: "{url}" to {cached_file}\n')
+ hash_prefix = None
+ if check_hash:
+ r = HASH_REGEX.search(filename) # r is Optional[Match[str]]
+ hash_prefix = r.group(1) if r else None
+ download_url_to_file(url, cached_file, hash_prefix, progress=progress)
+
+ return cached_file
diff --git a/kornia/feature/lightglue_onnx/utils/keypoints.py b/kornia/feature/lightglue_onnx/utils/keypoints.py
new file mode 100644
index 000000000..668b0edfa
--- /dev/null
+++ b/kornia/feature/lightglue_onnx/utils/keypoints.py
@@ -0,0 +1,14 @@
+from __future__ import annotations
+
+import torch
+
+from kornia.core import Tensor, tensor
+
+
+def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor:
+ if isinstance(size, torch.Size):
+ size = tensor(size)[None]
+ shift = size.float().to(kpts) / 2
+ scale = size.max(1).values.float().to(kpts) / 2
+ kpts = (kpts - shift[:, None]) / scale[:, None, None]
+ return kpts
diff --git a/requirements/requirements-dev.txt b/requirements/requirements-dev.txt
index 90bc16164..5bbe4d688 100644
--- a/requirements/requirements-dev.txt
+++ b/requirements/requirements-dev.txt
@@ -3,6 +3,7 @@ kornia-rs==0.0.8
mypy[reports]
numpy
onnx
+onnxruntime-gpu>=1.16; sys_platform != 'darwin'
pre-commit>=2
pydocstyle
pytest==7.4.2
diff --git a/test/feature/test_lightglue_onnx.py b/test/feature/test_lightglue_onnx.py
new file mode 100644
index 000000000..b0b12e894
--- /dev/null
+++ b/test/feature/test_lightglue_onnx.py
@@ -0,0 +1,105 @@
+import pytest
+import torch
+
+from kornia.feature import OnnxLightGlue
+from kornia.feature.lightglue_onnx.utils import normalize_keypoints
+
+try:
+ import onnxruntime as ort
+except ImportError:
+ ort = None
+
+
[email protected](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)
+ assert model is not None
+
+ @pytest.mark.slow
+ def test_forward(self):
+ model = OnnxLightGlue()
+
+ 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)
+ outputs = model(
+ {
+ "image0": {"keypoints": kpts, "descriptors": desc, "image": image},
+ "image1": {"keypoints": kpts, "descriptors": desc, "image": image},
+ }
+ )
+
+ assert "matches" in outputs
+ assert "scores" in outputs
+
+ def test_normalize_keypoints(self):
+ kpts = torch.randint(0, 100, (1, 5, 2))
+ size = torch.tensor([[100, 100]])
+ kpts = normalize_keypoints(kpts, size)
+ assert torch.all(torch.abs(kpts) <= 1).item()
+
+ @pytest.mark.slow
+ def test_exception(self):
+ with pytest.raises(RuntimeError) as e:
+ OnnxLightGlue(device="invalid device")
+ assert "Invalid device string: 'invalid device'" in str(e)
+
+ model = OnnxLightGlue()
+
+ 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)
+
+ # Missing input
+ with pytest.raises(Exception) as e:
+ model({"image0": {"keypoints": kpts, "descriptors": desc, "image": image}})
+ assert "Missing key image1 in data" in str(e)
+
+ # Wrong dtype
+ with pytest.raises(Exception) as e:
+ model(
+ {
+ "image0": {
+ "keypoints": torch.zeros(1, 5, 2, dtype=torch.int32, device=device),
+ "descriptors": desc,
+ "image": image,
+ },
+ "image1": {"keypoints": kpts, "descriptors": desc, "image": image},
+ }
+ )
+ assert "Wrong dtype" in str(e)
+
+ # Wrong device
+ with pytest.raises(Exception) as e:
+ model(
+ {
+ "image0": {"keypoints": torch.zeros(1, 5, 2, device="cpu"), "descriptors": desc, "image": image},
+ "image1": {"keypoints": kpts, "descriptors": desc, "image": image},
+ }
+ )
+ assert "Wrong device" in str(e)
+
+ # Wrong shapes
+ with pytest.raises(Exception) as e:
+ model(
+ {
+ "image0": {"keypoints": torch.zeros(1, 4, 2, device=device), "descriptors": desc, "image": image},
+ "image1": {"keypoints": kpts, "descriptors": desc, "image": image},
+ }
+ )
+ assert "Number of keypoints does not match number of descriptors" in str(e)
+
+ with pytest.raises(Exception) as e:
+ model(
+ {
+ "image0": {"keypoints": kpts, "descriptors": torch.zeros(1, 5, 127, device=device), "image": image},
+ "image1": {"keypoints": kpts, "descriptors": desc, "image": image},
+ }
+ )
+ assert "Descriptors' dimensions do not match" in str(e)