π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): lazy-import onnxruntime and numpy in OnnxLightGlue (#4295)
Dmytro Mishkine2e7b7f34b0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 63cca7504..9738fd3e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -310,6 +310,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `import kornia` no longer imports onnxruntime when it is installed (#4295)* DeDoDe's vendored DINOv2 no longer probes for `xformers`; the pure-PyTorch path it always ran is theonly one. (#4288)* `kornia.feature.LightGlue` no longer probes for `flash_attn`; the SDPA path it always used is nowdiff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.pyindex ebb25d864..abd5d1b72 100644--- a/kornia/feature/lightglue_onnx/lightglue.py+++ b/kornia/feature/lightglue_onnx/lightglue.py@@ -17,21 +17,17 @@from __future__ import annotations+import importlib.utilfrom typing import ClassVar, Unionimport torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE+from kornia.core.external import numpy as np+from kornia.core.external import onnxruntime as ortfrom .utils import download_onnx_from_url, normalize_keypoints-try:- import numpy as _np # noqa: ICN001- import onnxruntime as _ort-except ImportError:- _np = None # type: ignore- _ort = None-__all__ = ["OnnxLightGlue"]@@ -62,8 +58,8 @@ class OnnxLightGlue:required_data_keys: ClassVar[list[str]] = ["image0", "image1"]def __init__(self, weights: str | None = None, device: Union[str, torch.device, None] = "cpu") -> None:- KORNIA_CHECK(_ort is not None, "onnxruntime is not installed.")- KORNIA_CHECK(_np is not None, "numpy is not installed.")+ KORNIA_CHECK(importlib.util.find_spec("onnxruntime") is not None, "onnxruntime is not installed.")+ KORNIA_CHECK(importlib.util.find_spec("numpy") is not None, "numpy is not installed.")device = torch.device(device) # type: ignoreself.device = device@@ -88,7 +84,7 @@ class OnnxLightGlue:weights = download_onnx_from_url(url)- self.session = _ort.InferenceSession(weights, providers=providers)+ self.session = ort.InferenceSession(weights, providers=providers)def __call__(self, data: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:"""Run the ONNX LightGlue matcher.@@ -173,7 +169,7 @@ class OnnxLightGlue:name,device_type=self.device.type,device_id=0,- element_type=_np.float32,+ element_type=np.float32,shape=tuple(tensor.shape),buffer_ptr=tensor.data_ptr(),)diff --git a/tests/test_import.py b/tests/test_import.pyindex 3c85b8bc1..05da2e781 100644--- a/tests/test_import.py+++ b/tests/test_import.py@@ -18,6 +18,9 @@import subprocessimport sysimport textwrap+from pathlib import Path++import pytestdef test_import_without_jit_script_deprecation():@@ -78,9 +81,10 @@ def test_import_emits_no_warnings():import torch # noqa: F401 # torch's own import warnings are not kornia's to fix- # Same for onnxruntime, which kornia.feature.lightglue_onnx imports eagerly when- # installed: its import-time platform warnings (e.g. "Unsupported Windows version- # (2025server)" on windows-2025 runners) are not kornia's to fix either.+ # Same for onnxruntime, if installed: its import-time platform warnings (e.g.+ # "Unsupported Windows version (2025server)" on windows-2025 runners) are not+ # kornia's to fix either. `import kornia` no longer imports onnxruntime eagerly+ # (kornia#4260), but pre-importing it here keeps the guard robust regardless.with contextlib.suppress(ImportError):import onnxruntime # noqa: F401@@ -97,3 +101,33 @@ def test_import_emits_no_warnings():timeout=300,)assert result.returncode == 0, f"importing kornia emitted a warning:\n{result.stderr}"+++def test_import_kornia_does_not_import_onnxruntime():+ """``import kornia`` must not eagerly load onnxruntime, even when it is installed.++ ``kornia.feature.lightglue_onnx`` used to import onnxruntime at module level, so a plain+ ``import kornia`` loaded the ORT native extension for a class nobody had instantiated.+ Every ONNX consumer now goes through the ``LazyLoader`` handles in+ ``kornia.core.external``; this pin keeps it that way. See+ https://github.com/kornia/kornia/issues/4260.++ Skipped when onnxruntime is not installed, otherwise the assertion is vacuous. The child+ interpreter runs with the repository root as its working directory so it imports the same+ ``kornia`` as this session, even when kornia is installed editable from another checkout.+ """+ pytest.importorskip("onnxruntime")++ import kornia++ repo_root = Path(kornia.__file__).resolve().parents[1]+ result = subprocess.run(+ [sys.executable, "-c", "import kornia, sys; print('onnxruntime' in sys.modules)"],+ cwd=repo_root,+ capture_output=True,+ text=True,+ check=False,+ timeout=300,+ )+ assert result.returncode == 0, f"importing kornia failed:\n{result.stderr}"+ assert result.stdout.strip() == "False", f"import kornia loaded onnxruntime:\n{result.stdout}{result.stderr}"