Skip to content

Commit a2a984e

Browse files
committed
dev(narugo): add docs for this submodule
1 parent 45ddfcb commit a2a984e

1 file changed

Lines changed: 87 additions & 11 deletions

File tree

imgutils/utils/onnxruntime.py

Lines changed: 87 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
"""
22
Overview:
3-
Management of onnx models.
3+
Management of ONNX models with automatic runtime detection and provider selection.
4+
5+
This module provides utilities for loading and managing ONNX models with support for
6+
different execution providers (CPU, CUDA, TensorRT). It automatically handles the
7+
installation of onnxruntime based on the system configuration and provides a
8+
convenient interface for model inference.
49
"""
510
import logging
611
import os
712
import shutil
13+
import warnings
814
from typing import Optional
915

1016
from hbutils.system import pip_install
@@ -15,6 +21,14 @@
1521

1622

1723
def _ensure_onnxruntime():
24+
"""
25+
Ensure that onnxruntime is installed on the system.
26+
27+
This function automatically detects if NVIDIA GPU is available and installs
28+
the appropriate version of onnxruntime (GPU or CPU version).
29+
30+
:raises ImportError: If installation fails
31+
"""
1832
try:
1933
import onnxruntime
2034
except (ImportError, ModuleNotFoundError):
@@ -39,13 +53,35 @@ def _ensure_onnxruntime():
3953

4054
def get_onnx_provider(provider: Optional[str] = None):
4155
"""
42-
Overview:
43-
Get onnx provider.
56+
Get the appropriate ONNX execution provider based on system capabilities and user preference.
57+
58+
This function automatically detects available execution providers and returns the most
59+
suitable one. It supports aliases for common providers and falls back to CPU execution
60+
if GPU providers are not available.
4461
4562
:param provider: The provider for ONNX runtime. ``None`` by default and will automatically detect
4663
if the ``CUDAExecutionProvider`` is available. If it is available, it will be used,
47-
otherwise the default ``CPUExecutionProvider`` will be used.
48-
:return: String of the provider.
64+
otherwise the default ``CPUExecutionProvider`` will be used. Supported aliases include
65+
'gpu' for CUDAExecutionProvider and 'trt' for TensorrtExecutionProvider.
66+
:type provider: Optional[str]
67+
68+
:return: String name of the selected execution provider.
69+
:rtype: str
70+
71+
:raises ValueError: If the specified provider is not supported or available.
72+
73+
Example::
74+
>>> # Auto-detect provider
75+
>>> provider = get_onnx_provider()
76+
>>> print(provider) # 'CUDAExecutionProvider' or 'CPUExecutionProvider'
77+
78+
>>> # Explicitly request GPU provider
79+
>>> provider = get_onnx_provider('gpu')
80+
>>> print(provider) # 'CUDAExecutionProvider'
81+
82+
>>> # Request CPU provider
83+
>>> provider = get_onnx_provider('cpu')
84+
>>> print(provider) # 'CPUExecutionProvider'
4985
"""
5086
if not provider:
5187
if "CUDAExecutionProvider" in get_available_providers():
@@ -65,6 +101,24 @@ def get_onnx_provider(provider: Optional[str] = None):
65101

66102
def _open_onnx_model(ckpt: str, provider: str, use_cpu: bool = True,
67103
cuda_device_id: Optional[int] = None) -> InferenceSession:
104+
"""
105+
Internal function to create and configure an ONNX inference session.
106+
107+
This function handles the low-level configuration of the ONNX runtime session,
108+
including optimization settings and provider-specific configurations.
109+
110+
:param ckpt: Path to the ONNX model file.
111+
:type ckpt: str
112+
:param provider: Name of the execution provider to use.
113+
:type provider: str
114+
:param use_cpu: Whether to include CPU provider as fallback. Defaults to True.
115+
:type use_cpu: bool
116+
:param cuda_device_id: Specific CUDA device ID to use for GPU inference.
117+
:type cuda_device_id: Optional[int]
118+
119+
:return: Configured ONNX inference session.
120+
:rtype: InferenceSession
121+
"""
68122
options = SessionOptions()
69123
options.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
70124
if provider == "CPUExecutionProvider":
@@ -75,6 +129,9 @@ def _open_onnx_model(ckpt: str, provider: str, use_cpu: bool = True,
75129
('CUDAExecutionProvider', {'device_id': cuda_device_id}),
76130
]
77131
else:
132+
if provider != 'CUDAExecutionProvider' and cuda_device_id is not None:
133+
warnings.warn(UserWarning(
134+
'CUDA device ID specified but provider is not CUDAExecutionProvider. The device ID will be ignored.'))
78135
providers = [provider]
79136
if use_cpu and "CPUExecutionProvider" not in providers:
80137
providers.append("CPUExecutionProvider")
@@ -85,19 +142,38 @@ def _open_onnx_model(ckpt: str, provider: str, use_cpu: bool = True,
85142

86143
def open_onnx_model(ckpt: str, mode: str = None, cuda_device_id: Optional[int] = None) -> InferenceSession:
87144
"""
88-
Overview:
89-
Open an ONNX model and load its ONNX runtime.
145+
Open an ONNX model and create a configured inference session.
146+
147+
This function provides a high-level interface for loading ONNX models with
148+
automatic provider selection and optimization. It supports environment variable
149+
configuration for runtime provider selection.
90150
91-
:param ckpt: ONNX model file.
92-
:param mode: Provider of the ONNX. Default is ``None`` which means the provider will be auto-detected,
93-
see :func:`get_onnx_provider` for more details.
94-
:return: A loaded ONNX runtime object.
151+
:param ckpt: Path to the ONNX model file to load.
152+
:type ckpt: str
153+
:param mode: Provider of the ONNX runtime. Default is ``None`` which means the provider will be auto-detected,
154+
see :func:`get_onnx_provider` for more details. Can also be controlled via ONNX_MODE environment variable.
155+
:type mode: Optional[str]
156+
:param cuda_device_id: Specific CUDA device ID to use for GPU inference. Only effective when using CUDA provider.
157+
:type cuda_device_id: Optional[int]
158+
159+
:return: A loaded and configured ONNX inference session ready for prediction.
160+
:rtype: InferenceSession
95161
96162
.. note::
97163
When ``mode`` is set to ``None``, it will attempt to detect the environment variable ``ONNX_MODE``.
98164
This means you can decide which ONNX runtime to use by setting the environment variable. For example,
99165
on Linux, executing ``export ONNX_MODE=cpu`` will ignore any existing CUDA and force the model inference
100166
to run on CPU.
167+
168+
Example::
169+
>>> # Load model with auto-detected provider
170+
>>> session = open_onnx_model('model.onnx')
171+
172+
>>> # Force CPU execution
173+
>>> session = open_onnx_model('model.onnx', mode='cpu')
174+
175+
>>> # Use specific CUDA device
176+
>>> session = open_onnx_model('model.onnx', mode='gpu', cuda_device_id=1)
101177
"""
102178
return _open_onnx_model(
103179
ckpt=ckpt,

0 commit comments

Comments
 (0)