onnxruntime_inference_collection.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License.
  4. # --------------------------------------------------------------------------
  5. from __future__ import annotations
  6. import collections
  7. import collections.abc
  8. import os
  9. import typing
  10. import warnings
  11. from collections.abc import Callable, Sequence
  12. from typing import Any
  13. from onnxruntime.capi import _pybind_state as C
  14. if typing.TYPE_CHECKING:
  15. import numpy as np
  16. import numpy.typing as npt
  17. import onnxruntime
  18. def get_ort_device_type(device_type: str) -> int:
  19. if device_type == "cuda":
  20. return C.OrtDevice.cuda()
  21. elif device_type == "cann":
  22. return C.OrtDevice.cann()
  23. elif device_type == "cpu":
  24. return C.OrtDevice.cpu()
  25. elif device_type == "dml":
  26. return C.OrtDevice.dml()
  27. elif device_type == "webgpu":
  28. return C.OrtDevice.webgpu()
  29. elif device_type == "gpu":
  30. return C.OrtDevice.gpu()
  31. elif device_type == "npu":
  32. return C.OrtDevice.npu()
  33. else:
  34. raise Exception("Unsupported device type: " + device_type)
  35. class AdapterFormat:
  36. """
  37. This class is used to create adapter files from python structures
  38. """
  39. def __init__(self, adapter=None) -> None:
  40. if adapter is None:
  41. self._adapter = C.AdapterFormat()
  42. else:
  43. self._adapter = adapter
  44. @staticmethod
  45. def read_adapter(file_path: os.PathLike) -> AdapterFormat:
  46. return AdapterFormat(C.AdapterFormat.read_adapter(file_path))
  47. def export_adapter(self, file_path: os.PathLike):
  48. """
  49. This function writes a file at the specified location
  50. in onnxrunitme adapter format containing Lora parameters.
  51. :param file_path: absolute path for the adapter
  52. """
  53. self._adapter.export_adapter(file_path)
  54. def get_format_version(self) -> int:
  55. return self._adapter.format_version
  56. def set_adapter_version(self, adapter_version: int) -> None:
  57. self._adapter.adapter_version = adapter_version
  58. def get_adapter_version(self) -> int:
  59. return self._adapter.adapter_version
  60. def set_model_version(self, model_version: int) -> None:
  61. self._adapter.model_version = model_version
  62. def get_model_version(self) -> int:
  63. return self._adapter.model_version
  64. def set_parameters(self, params: dict[str, OrtValue]) -> None:
  65. self._adapter.parameters = {k: v._ortvalue for k, v in params.items()}
  66. def get_parameters(self) -> dict[str, OrtValue]:
  67. return {k: OrtValue(v) for k, v in self._adapter.parameters.items()}
  68. def check_and_normalize_provider_args(
  69. providers: Sequence[str | tuple[str, dict[Any, Any]]] | None,
  70. provider_options: Sequence[dict[Any, Any]] | None,
  71. available_provider_names: Sequence[str],
  72. ):
  73. """
  74. Validates the 'providers' and 'provider_options' arguments and returns a
  75. normalized version.
  76. :param providers: Optional sequence of providers in order of decreasing
  77. precedence. Values can either be provider names or tuples of
  78. (provider name, options dict).
  79. :param provider_options: Optional sequence of options dicts corresponding
  80. to the providers listed in 'providers'.
  81. :param available_provider_names: The available provider names.
  82. :return: Tuple of (normalized 'providers' sequence, normalized
  83. 'provider_options' sequence).
  84. 'providers' can contain either names or names and options. When any options
  85. are given in 'providers', 'provider_options' should not be used.
  86. The normalized result is a tuple of:
  87. 1. Sequence of provider names in the same order as 'providers'.
  88. 2. Sequence of corresponding provider options dicts with string keys and
  89. values. Unspecified provider options yield empty dicts.
  90. """
  91. if providers is None:
  92. return [], []
  93. provider_name_to_options = collections.OrderedDict()
  94. def set_provider_options(name, options):
  95. if name not in available_provider_names:
  96. warnings.warn(
  97. "Specified provider '{}' is not in available provider names.Available providers: '{}'".format(
  98. name, ", ".join(available_provider_names)
  99. )
  100. )
  101. if name in provider_name_to_options:
  102. warnings.warn(f"Duplicate provider '{name}' encountered, ignoring.")
  103. return
  104. normalized_options = {str(key): str(value) for key, value in options.items()}
  105. provider_name_to_options[name] = normalized_options
  106. if not isinstance(providers, collections.abc.Sequence):
  107. raise ValueError("'providers' should be a sequence.")
  108. if provider_options is not None:
  109. if not isinstance(provider_options, collections.abc.Sequence):
  110. raise ValueError("'provider_options' should be a sequence.")
  111. if len(providers) != len(provider_options):
  112. raise ValueError("'providers' and 'provider_options' should be the same length if both are given.")
  113. if not all(isinstance(provider, str) for provider in providers):
  114. raise ValueError("Only string values for 'providers' are supported if 'provider_options' is given.")
  115. if not all(isinstance(options_for_provider, dict) for options_for_provider in provider_options):
  116. raise ValueError("'provider_options' values must be dicts.")
  117. for name, options in zip(providers, provider_options, strict=False):
  118. set_provider_options(name, options)
  119. else:
  120. for provider in providers:
  121. if isinstance(provider, str):
  122. set_provider_options(provider, {})
  123. elif (
  124. isinstance(provider, tuple)
  125. and len(provider) == 2
  126. and isinstance(provider[0], str)
  127. and isinstance(provider[1], dict)
  128. ):
  129. set_provider_options(provider[0], provider[1])
  130. else:
  131. raise ValueError("'providers' values must be either strings or (string, dict) tuples.")
  132. return list(provider_name_to_options.keys()), list(provider_name_to_options.values())
  133. class Session:
  134. """
  135. This is the main class used to run a model.
  136. """
  137. def __init__(self, enable_fallback: bool = True):
  138. # self._sess is managed by the derived class and relies on bindings from C.InferenceSession
  139. self._sess = None
  140. self._enable_fallback = enable_fallback
  141. def get_session_options(self) -> onnxruntime.SessionOptions:
  142. "Return the session options. See :class:`onnxruntime.SessionOptions`."
  143. return self._sess_options
  144. def get_inputs(self) -> Sequence[onnxruntime.NodeArg]:
  145. "Return the inputs metadata as a list of :class:`onnxruntime.NodeArg`."
  146. return self._inputs_meta
  147. def get_outputs(self) -> Sequence[onnxruntime.NodeArg]:
  148. "Return the outputs metadata as a list of :class:`onnxruntime.NodeArg`."
  149. return self._outputs_meta
  150. def get_overridable_initializers(self) -> Sequence[onnxruntime.NodeArg]:
  151. "Return the inputs (including initializers) metadata as a list of :class:`onnxruntime.NodeArg`."
  152. return self._overridable_initializers
  153. def get_modelmeta(self) -> onnxruntime.ModelMetadata:
  154. "Return the metadata. See :class:`onnxruntime.ModelMetadata`."
  155. return self._model_meta
  156. def get_input_memory_infos(self) -> Sequence[onnxruntime.MemoryInfo]:
  157. "Return the memory info for the inputs."
  158. return self._input_meminfos
  159. def get_output_memory_infos(self) -> Sequence[onnxruntime.MemoryInfo]:
  160. "Return the memory info for the outputs."
  161. return self._output_meminfos
  162. def get_input_epdevices(self) -> Sequence[onnxruntime.OrtEpDevice]:
  163. "Return the execution providers for the inputs."
  164. return self._input_epdevices
  165. def get_providers(self) -> Sequence[str]:
  166. "Return list of registered execution providers."
  167. return self._providers
  168. def get_provider_options(self):
  169. "Return registered execution providers' configurations."
  170. return self._provider_options
  171. def get_provider_graph_assignment_info(self) -> Sequence[onnxruntime.OrtEpAssignedSubgraph]:
  172. """
  173. Get information about the subgraphs assigned to each execution provider and the nodes within.
  174. Application must enable the recording of graph assignment information by setting the session configuration
  175. for the key "session.record_ep_graph_assignment_info" to "1".
  176. """
  177. return self._sess.get_provider_graph_assignment_info()
  178. def set_providers(self, providers=None, provider_options=None) -> None:
  179. """
  180. Register the input list of execution providers. The underlying session is re-created.
  181. :param providers: Optional sequence of providers in order of decreasing
  182. precedence. Values can either be provider names or tuples of
  183. (provider name, options dict). If not provided, then all available
  184. providers are used with the default precedence.
  185. :param provider_options: Optional sequence of options dicts corresponding
  186. to the providers listed in 'providers'.
  187. 'providers' can contain either names or names and options. When any options
  188. are given in 'providers', 'provider_options' should not be used.
  189. The list of providers is ordered by precedence. For example
  190. `['CUDAExecutionProvider', 'CPUExecutionProvider']`
  191. means execute a node using CUDAExecutionProvider if capable,
  192. otherwise execute using CPUExecutionProvider.
  193. """
  194. # recreate the underlying C.InferenceSession
  195. self._reset_session(providers, provider_options)
  196. def disable_fallback(self) -> None:
  197. """
  198. Disable session.run() fallback mechanism.
  199. """
  200. self._enable_fallback = False
  201. def enable_fallback(self) -> None:
  202. """
  203. Enable session.Run() fallback mechanism. If session.Run() fails due to an internal Execution Provider failure,
  204. reset the Execution Providers enabled for this session.
  205. If GPU is enabled, fall back to CUDAExecutionProvider.
  206. otherwise fall back to CPUExecutionProvider.
  207. """
  208. self._enable_fallback = True
  209. def _validate_input(self, feed_input_names):
  210. missing_input_names = []
  211. for input in self._inputs_meta:
  212. if input.name not in feed_input_names and not input.type.startswith("optional"):
  213. missing_input_names.append(input.name)
  214. if missing_input_names:
  215. raise ValueError(
  216. f"Required inputs ({missing_input_names}) are missing from input feed ({feed_input_names})."
  217. )
  218. def run(self, output_names, input_feed, run_options=None) -> Sequence[np.ndarray | SparseTensor | list | dict]:
  219. """
  220. Compute the predictions.
  221. :param output_names: name of the outputs
  222. :param input_feed: dictionary ``{ input_name: input_value }``
  223. :param run_options: See :class:`onnxruntime.RunOptions`.
  224. :return: list of results, every result is either a numpy array,
  225. a sparse tensor, a list or a dictionary.
  226. ::
  227. sess.run([output_name], {input_name: x})
  228. """
  229. self._validate_input(list(input_feed.keys()))
  230. if not output_names:
  231. output_names = [output.name for output in self._outputs_meta]
  232. try:
  233. return self._sess.run(output_names, input_feed, run_options)
  234. except C.EPFail as err:
  235. if self._enable_fallback:
  236. print(f"EP Error: {err!s} using {self._providers}")
  237. print(f"Falling back to {self._fallback_providers} and retrying.")
  238. self.set_providers(self._fallback_providers)
  239. # Fallback only once.
  240. self.disable_fallback()
  241. return self._sess.run(output_names, input_feed, run_options)
  242. raise
  243. def run_async(self, output_names, input_feed, callback, user_data, run_options=None):
  244. """
  245. Compute the predictions asynchronously in a separate cxx thread from ort intra-op threadpool.
  246. :param output_names: name of the outputs
  247. :param input_feed: dictionary ``{ input_name: input_value }``
  248. :param callback: python function that accept array of results, and a status string on error.
  249. The callback will be invoked by a cxx thread from ort intra-op threadpool.
  250. :param run_options: See :class:`onnxruntime.RunOptions`.
  251. ::
  252. class MyData:
  253. def __init__(self):
  254. # ...
  255. def save_results(self, results):
  256. # ...
  257. def callback(results: np.ndarray, user_data: MyData, err: str) -> None:
  258. if err:
  259. print (err)
  260. else:
  261. # save results to user_data
  262. sess.run_async([output_name], {input_name: x}, callback)
  263. """
  264. self._validate_input(list(input_feed.keys()))
  265. if not output_names:
  266. output_names = [output.name for output in self._outputs_meta]
  267. return self._sess.run_async(output_names, input_feed, callback, user_data, run_options)
  268. def run_with_ort_values(self, output_names, input_dict_ort_values, run_options=None) -> Sequence[OrtValue]:
  269. """
  270. Compute the predictions.
  271. :param output_names: name of the outputs
  272. :param input_dict_ort_values: dictionary ``{ input_name: input_ort_value }``
  273. See ``OrtValue`` class how to create `OrtValue`
  274. from numpy array or `SparseTensor`
  275. :param run_options: See :class:`onnxruntime.RunOptions`.
  276. :return: an array of `OrtValue`
  277. ::
  278. sess.run([output_name], {input_name: x})
  279. """
  280. def invoke(sess, output_names, input_dict_ort_values, run_options):
  281. input_dict = {}
  282. for n, v in input_dict_ort_values.items():
  283. input_dict[n] = v._get_c_value()
  284. result = sess.run_with_ort_values(input_dict, output_names, run_options)
  285. if not isinstance(result, C.OrtValueVector):
  286. raise TypeError("run_with_ort_values() must return a instance of type 'OrtValueVector'.")
  287. ort_values = [OrtValue(v) for v in result]
  288. return ort_values
  289. self._validate_input(list(input_dict_ort_values.keys()))
  290. if not output_names:
  291. output_names = [output.name for output in self._outputs_meta]
  292. try:
  293. return invoke(self._sess, output_names, input_dict_ort_values, run_options)
  294. except C.EPFail as err:
  295. if self._enable_fallback:
  296. print(f"EP Error: {err!s} using {self._providers}")
  297. print(f"Falling back to {self._fallback_providers} and retrying.")
  298. self.set_providers(self._fallback_providers)
  299. # Fallback only once.
  300. self.disable_fallback()
  301. return invoke(self._sess, output_names, input_dict_ort_values, run_options)
  302. raise
  303. def end_profiling(self):
  304. """
  305. End profiling and return results in a file.
  306. The results are stored in a filename if the option
  307. :meth:`onnxruntime.SessionOptions.enable_profiling`.
  308. """
  309. return self._sess.end_profiling()
  310. def get_profiling_start_time_ns(self):
  311. """
  312. Return the nanoseconds of profiling's start time
  313. Comparable to time.monotonic_ns() after Python 3.3
  314. On some platforms, this timer may not be as precise as nanoseconds
  315. For instance, on Windows and MacOS, the precision will be ~100ns
  316. """
  317. return self._sess.get_profiling_start_time_ns
  318. def io_binding(self) -> IOBinding:
  319. "Return an onnxruntime.IOBinding object`."
  320. return IOBinding(self)
  321. def run_with_iobinding(self, iobinding, run_options=None):
  322. """
  323. Compute the predictions.
  324. :param iobinding: the iobinding object that has graph inputs/outputs bind.
  325. :param run_options: See :class:`onnxruntime.RunOptions`.
  326. """
  327. self._sess.run_with_iobinding(iobinding._iobinding, run_options)
  328. def set_ep_dynamic_options(self, options: dict[str, str]):
  329. """
  330. Set dynamic options for execution providers.
  331. :param options: Dictionary of key-value pairs where both keys and values are strings.
  332. These options will be passed to the execution providers to modify
  333. their runtime behavior.
  334. """
  335. self._sess.set_ep_dynamic_options(options)
  336. def get_tuning_results(self):
  337. return self._sess.get_tuning_results()
  338. def set_tuning_results(self, results, *, error_on_invalid=False):
  339. return self._sess.set_tuning_results(results, error_on_invalid)
  340. def run_with_ortvaluevector(self, run_options, feed_names, feeds, fetch_names, fetches, fetch_devices):
  341. """
  342. Compute the predictions similar to other run_*() methods but with minimal C++/Python conversion overhead.
  343. :param run_options: See :class:`onnxruntime.RunOptions`.
  344. :param feed_names: list of input names.
  345. :param feeds: list of input OrtValue.
  346. :param fetch_names: list of output names.
  347. :param fetches: list of output OrtValue.
  348. :param fetch_devices: list of output devices.
  349. """
  350. self._sess.run_with_ortvaluevector(run_options, feed_names, feeds, fetch_names, fetches, fetch_devices)
  351. class InferenceSession(Session):
  352. """
  353. This is the main class used to run a model.
  354. """
  355. def __init__(
  356. self,
  357. path_or_bytes: str | bytes | os.PathLike,
  358. sess_options: onnxruntime.SessionOptions | None = None,
  359. providers: Sequence[str | tuple[str, dict[Any, Any]]] | None = None,
  360. provider_options: Sequence[dict[Any, Any]] | None = None,
  361. **kwargs,
  362. ) -> None:
  363. """
  364. :param path_or_bytes: Filename or serialized ONNX or ORT format model in a byte string.
  365. :param sess_options: Session options.
  366. :param providers: Optional sequence of providers in order of decreasing
  367. precedence. Values can either be provider names or tuples of
  368. (provider name, options dict). If not provided, then all available
  369. providers are used with the default precedence.
  370. :param provider_options: Optional sequence of options dicts corresponding
  371. to the providers listed in 'providers'.
  372. The model type will be inferred unless explicitly set in the SessionOptions.
  373. To explicitly set:
  374. ::
  375. so = onnxruntime.SessionOptions()
  376. # so.add_session_config_entry('session.load_model_format', 'ONNX') or
  377. so.add_session_config_entry('session.load_model_format', 'ORT')
  378. A file extension of '.ort' will be inferred as an ORT format model.
  379. All other filenames are assumed to be ONNX format models.
  380. 'providers' can contain either names or names and options. When any options
  381. are given in 'providers', 'provider_options' should not be used.
  382. The list of providers is ordered by precedence. For example
  383. `['CUDAExecutionProvider', 'CPUExecutionProvider']`
  384. means execute a node using `CUDAExecutionProvider`
  385. if capable, otherwise execute using `CPUExecutionProvider`.
  386. """
  387. super().__init__(enable_fallback=int(kwargs.get("enable_fallback", 1)) == 1)
  388. if isinstance(path_or_bytes, (str, os.PathLike)):
  389. self._model_path = os.fspath(path_or_bytes)
  390. self._model_bytes = None
  391. elif isinstance(path_or_bytes, bytes):
  392. self._model_path = None
  393. self._model_bytes = path_or_bytes # TODO: This is bad as we're holding the memory indefinitely
  394. else:
  395. raise TypeError(f"Unable to load from type '{type(path_or_bytes)}'")
  396. self._sess_options = sess_options
  397. self._sess_options_initial = sess_options
  398. if "read_config_from_model" in kwargs:
  399. self._read_config_from_model = int(kwargs["read_config_from_model"]) == 1
  400. else:
  401. self._read_config_from_model = os.environ.get("ORT_LOAD_CONFIG_FROM_MODEL") == "1"
  402. # internal parameters that we don't expect to be used in general so aren't documented
  403. disabled_optimizers = kwargs.get("disabled_optimizers")
  404. try:
  405. self._create_inference_session(providers, provider_options, disabled_optimizers)
  406. except (ValueError, RuntimeError) as e:
  407. if self._enable_fallback:
  408. try:
  409. print("*************** EP Error ***************")
  410. print(f"EP Error {e} when using {providers}")
  411. print(f"Falling back to {self._fallback_providers} and retrying.")
  412. print("****************************************")
  413. self._create_inference_session(self._fallback_providers, None)
  414. # Fallback only once.
  415. self.disable_fallback()
  416. return
  417. except Exception as fallback_error:
  418. raise fallback_error from e
  419. # Fallback is disabled. Raise the original error.
  420. raise e
  421. def _create_inference_session(self, providers, provider_options, disabled_optimizers=None):
  422. available_providers = C.get_available_providers()
  423. # Validate that TensorrtExecutionProvider and NvTensorRTRTXExecutionProvider are not both specified
  424. if providers:
  425. has_tensorrt = any(
  426. provider == "TensorrtExecutionProvider"
  427. or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
  428. for provider in providers
  429. )
  430. has_tensorrt_rtx = any(
  431. provider == "NvTensorRTRTXExecutionProvider"
  432. or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider")
  433. for provider in providers
  434. )
  435. if has_tensorrt and has_tensorrt_rtx:
  436. raise ValueError(
  437. "Cannot enable both 'TensorrtExecutionProvider' and 'NvTensorRTRTXExecutionProvider' "
  438. "in the same session."
  439. )
  440. # Tensorrt and TensorRT RTX can fall back to CUDA if it's explicitly assigned. All others fall back to CPU.
  441. if "NvTensorRTRTXExecutionProvider" in available_providers:
  442. if (
  443. providers
  444. and any(
  445. provider == "CUDAExecutionProvider"
  446. or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
  447. for provider in providers
  448. )
  449. and any(
  450. provider == "NvTensorRTRTXExecutionProvider"
  451. or (isinstance(provider, tuple) and provider[0] == "NvTensorRTRTXExecutionProvider")
  452. for provider in providers
  453. )
  454. ):
  455. self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
  456. else:
  457. self._fallback_providers = ["CPUExecutionProvider"]
  458. elif "TensorrtExecutionProvider" in available_providers:
  459. if (
  460. providers
  461. and any(
  462. provider == "CUDAExecutionProvider"
  463. or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
  464. for provider in providers
  465. )
  466. and any(
  467. provider == "TensorrtExecutionProvider"
  468. or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
  469. for provider in providers
  470. )
  471. ):
  472. self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
  473. else:
  474. self._fallback_providers = ["CPUExecutionProvider"]
  475. else:
  476. self._fallback_providers = ["CPUExecutionProvider"]
  477. # validate providers and provider_options before other initialization
  478. providers, provider_options = check_and_normalize_provider_args(
  479. providers, provider_options, available_providers
  480. )
  481. # Print a warning if user passed providers to InferenceSession() but the SessionOptions instance
  482. # already has provider information (e.g., via add_provider_for_devices()). The providers specified
  483. # here will take precedence.
  484. if self._sess_options is not None and (providers or provider_options) and self._sess_options.has_providers():
  485. warnings.warn(
  486. "Specified 'providers'/'provider_options' when creating InferenceSession but SessionOptions has "
  487. "already been configured with providers. InferenceSession will only use the providers "
  488. "passed to InferenceSession()."
  489. )
  490. session_options = self._sess_options if self._sess_options else C.get_default_session_options()
  491. self._register_ep_custom_ops(session_options, providers, provider_options, available_providers)
  492. if self._model_path:
  493. sess = C.InferenceSession(session_options, self._model_path, True, self._read_config_from_model)
  494. else:
  495. sess = C.InferenceSession(session_options, self._model_bytes, False, self._read_config_from_model)
  496. if disabled_optimizers is None:
  497. disabled_optimizers = set()
  498. elif not isinstance(disabled_optimizers, set):
  499. # convert to set. assumes iterable
  500. disabled_optimizers = set(disabled_optimizers)
  501. # initialize the C++ InferenceSession
  502. sess.initialize_session(providers, provider_options, disabled_optimizers)
  503. self._sess = sess
  504. self._sess_options = self._sess.session_options
  505. self._inputs_meta = self._sess.inputs_meta
  506. self._outputs_meta = self._sess.outputs_meta
  507. self._overridable_initializers = self._sess.overridable_initializers
  508. self._input_meminfos = self._sess.input_meminfos
  509. self._output_meminfos = self._sess.output_meminfos
  510. self._input_epdevices = self._sess.input_epdevices
  511. self._model_meta = self._sess.model_meta
  512. self._providers = self._sess.get_providers()
  513. self._provider_options = self._sess.get_provider_options()
  514. self._profiling_start_time_ns = self._sess.get_profiling_start_time_ns
  515. def _reset_session(self, providers, provider_options) -> None:
  516. "release underlying session object."
  517. # meta data references session internal structures
  518. # so they must be set to None to decrement _sess reference count.
  519. self._sess_options = None
  520. self._inputs_meta = None
  521. self._outputs_meta = None
  522. self._overridable_initializers = None
  523. self._input_meminfos = None
  524. self._output_meminfos = None
  525. self._input_epdevices = None
  526. self._model_meta = None
  527. self._providers = None
  528. self._provider_options = None
  529. self._profiling_start_time_ns = None
  530. # create a new C.InferenceSession
  531. self._sess = None
  532. self._sess_options = self._sess_options_initial
  533. self._create_inference_session(providers, provider_options)
  534. def _register_ep_custom_ops(self, session_options, providers, provider_options, available_providers):
  535. for i in range(len(providers)):
  536. if providers[i] in available_providers and providers[i] == "TensorrtExecutionProvider":
  537. C.register_tensorrt_plugins_as_custom_ops(session_options, provider_options[i])
  538. elif (
  539. isinstance(providers[i], tuple)
  540. and providers[i][0] in available_providers
  541. and providers[i][0] == "TensorrtExecutionProvider"
  542. ):
  543. C.register_tensorrt_plugins_as_custom_ops(session_options, providers[i][1])
  544. if providers[i] in available_providers and providers[i] == "NvTensorRTRTXExecutionProvider":
  545. C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, provider_options[i])
  546. elif (
  547. isinstance(providers[i], tuple)
  548. and providers[i][0] in available_providers
  549. and providers[i][0] == "NvTensorrtRTXExecutionProvider"
  550. ):
  551. C.register_nv_tensorrt_rtx_plugins_as_custom_ops(session_options, providers[i][1])
  552. def make_get_initializer_location_func_wrapper(
  553. get_initializer_location_func: GetInitializerLocationFunc,
  554. ) -> GetInitializerLocationWrapperFunc:
  555. """
  556. Wraps a user's "get initializer location" function. The returned wrapper function adheres to the
  557. signature expected by ORT.
  558. Need this wrapper to:
  559. - Convert the `initializer_value` parameter from `C.OrtValue` to `onnxruntime.OrtValue`, which is more
  560. convenient for the user's function to use.
  561. - Allow the user's function to return the original `external_info` parameter (this wrapper makes a copy)
  562. """
  563. def get_initializer_location_func_wrapper(
  564. initializer_name: str,
  565. initializer_value: C.OrtValue,
  566. external_info: C.OrtExternalInitializerInfo | None,
  567. ) -> C.OrtExternalInitializerInfo | None:
  568. ret_val: C.OrtExternalInitializerInfo | None = get_initializer_location_func(
  569. initializer_name, OrtValue(initializer_value), external_info
  570. )
  571. if ret_val is not None and ret_val == external_info:
  572. # User returned `external_info` (const and owned by ORT). ORT expects the returned value to be
  573. # a new instance (that it deletes), so make a copy.
  574. ret_val = C.OrtExternalInitializerInfo(ret_val.filepath, ret_val.file_offset, ret_val.byte_size)
  575. return ret_val
  576. return get_initializer_location_func_wrapper
  577. class ModelCompiler:
  578. """
  579. This class is used to compile an ONNX model. A compiled ONNX model has EPContext nodes that each
  580. encapsulates a subgraph compiled/optimized for a specific execution provider.
  581. Refer to the EPContext design document for more information about EPContext models:
  582. https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html
  583. ::
  584. sess_options = onnxruntime.SessionOptions()
  585. sess_options.add_provider("SomeExecutionProvider", {"option1": "value1"})
  586. # Alternatively, allow ONNX Runtime to select the provider automatically given a policy:
  587. # sess_options.set_provider_selection_policy(onnxrt.OrtExecutionProviderDevicePolicy.PREFER_NPU)
  588. model_compiler = onnxruntime.ModelCompiler(sess_options, "input_model.onnx")
  589. model_compiler.compile_to_file("output_model.onnx")
  590. """
  591. def __init__(
  592. self,
  593. sess_options: onnxruntime.SessionOptions,
  594. input_model_path_or_bytes: str | os.PathLike | bytes,
  595. embed_compiled_data_into_model: bool = False,
  596. external_initializers_file_path: str | os.PathLike | None = None,
  597. external_initializers_size_threshold: int = 1024,
  598. flags: int = C.OrtCompileApiFlags.NONE,
  599. graph_optimization_level: C.GraphOptimizationLevel = C.GraphOptimizationLevel.ORT_DISABLE_ALL,
  600. get_initializer_location_func: GetInitializerLocationFunc | None = None,
  601. ):
  602. """
  603. Creates a ModelCompiler instance.
  604. :param sess_options: Session options containing the providers for which the model will be compiled.
  605. Refer to SessionOptions.add_provider() and SessionOptions.set_provider_selection_policy().
  606. :param input_model_path_or_bytes: The path to the input model file or bytes representing a serialized
  607. ONNX model.
  608. :param embed_compiled_data_into_model: Defaults to False. Set to True to embed compiled binary data into
  609. EPContext nodes in the compiled model.
  610. :param external_initializers_file_path: Defaults to None. Set to a path for a file that will store the
  611. initializers for non-compiled nodes.
  612. :param external_initializers_size_threshold: Defaults to 1024. Ignored if `external_initializers_file_path`
  613. is None or empty. Initializers larger than this threshold are stored in the external initializers file.
  614. :param flags: Additional boolean options to enable. Set this parameter to a bitwise OR of
  615. flags in onnxruntime.OrtCompileApiFlags.
  616. :param graph_optimization_level: The graph optimization level.
  617. Defaults to onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL.
  618. :param get_initializer_location_func: Optional function called for every initializer to allow user to specify
  619. whether an initializer should be stored within the model or externally. Example:
  620. ```
  621. def get_initializer_location(
  622. initializer_name: str,
  623. initializer_value: onnxrt.OrtValue,
  624. external_info: onnxrt.OrtExternalInitializerInfo | None,
  625. ) -> onnxrt.OrtExternalInitializerInfo | None:
  626. byte_size = initializer_value.tensor_size_in_bytes()
  627. if byte_size < 64:
  628. return None # Store small initializer within compiled model.
  629. # Else, write initializer to new external file.
  630. value_np = initializer_value.numpy()
  631. file_offset = ext_init_file.tell()
  632. ext_init_file.write(value_np.tobytes())
  633. return onnxrt.OrtExternalInitializerInfo(initializer_file_path, file_offset, byte_size)
  634. ```
  635. """
  636. input_model_path: str | os.PathLike | None = None
  637. input_model_bytes: bytes | None = None
  638. if isinstance(input_model_path_or_bytes, (str, os.PathLike)):
  639. if not input_model_path_or_bytes:
  640. raise ValueError("Input model path is empty")
  641. input_model_path = os.fspath(input_model_path_or_bytes)
  642. elif isinstance(input_model_path_or_bytes, bytes):
  643. if len(input_model_path_or_bytes) == 0:
  644. raise ValueError("Input model bytes array is empty")
  645. input_model_bytes = input_model_path_or_bytes
  646. else:
  647. raise TypeError(f"Unable to load from type '{type(input_model_path_or_bytes)}'")
  648. if external_initializers_file_path:
  649. if not isinstance(external_initializers_file_path, (str, os.PathLike)):
  650. arg_type = type(external_initializers_file_path)
  651. raise TypeError(f"Output external initializer filepath is of unexpected type '{arg_type}'")
  652. external_initializers_file_path = os.fspath(external_initializers_file_path)
  653. else:
  654. external_initializers_file_path = ""
  655. if get_initializer_location_func is not None:
  656. if external_initializers_file_path:
  657. raise ValueError(
  658. "Cannot initialize ModelCompiler with both `external_initializers_file_path` "
  659. "and `get_initializer_location_func`"
  660. )
  661. self.get_initializer_location_func_wrapper = make_get_initializer_location_func_wrapper(
  662. get_initializer_location_func
  663. )
  664. else:
  665. self.get_initializer_location_func_wrapper = None
  666. if input_model_path:
  667. self._model_compiler = C.ModelCompiler(
  668. sess_options,
  669. input_model_path,
  670. True, # is path
  671. embed_compiled_data_into_model,
  672. external_initializers_file_path,
  673. external_initializers_size_threshold,
  674. flags,
  675. graph_optimization_level,
  676. self.get_initializer_location_func_wrapper,
  677. )
  678. else:
  679. self._model_compiler = C.ModelCompiler(
  680. sess_options,
  681. input_model_bytes,
  682. False, # is bytes
  683. embed_compiled_data_into_model,
  684. external_initializers_file_path,
  685. external_initializers_size_threshold,
  686. flags,
  687. graph_optimization_level,
  688. self.get_initializer_location_func_wrapper,
  689. )
  690. def compile_to_file(self, output_model_path: str | None = None):
  691. """
  692. Compiles to an output file. If an output file path is not provided,
  693. the output file path is generated based on the input model path by replacing
  694. '.onnx' with '_ctx.onnx'. Ex: The generated output file is 'model_ctx.onnx' for
  695. an input model with path 'model.onnx'.
  696. Raises an 'InvalidArgument' exception if the compilation options are invalid.
  697. :param output_model_path: Defaults to None. The path for the output/compiled model.
  698. """
  699. if output_model_path:
  700. if not isinstance(output_model_path, (str, os.PathLike)):
  701. raise TypeError(f"Output model's filepath is of unexpected type '{type(output_model_path)}'")
  702. output_model_path = os.fspath(output_model_path)
  703. self._model_compiler.compile_to_file(output_model_path)
  704. def compile_to_bytes(self) -> bytes:
  705. """
  706. Compiles to bytes representing the serialized compiled ONNX model.
  707. Raises an 'InvalidArgument' exception if the compilation options are invalid.
  708. :return: A bytes object representing the compiled ONNX model.
  709. """
  710. return self._model_compiler.compile_to_bytes()
  711. def compile_to_stream(self, write_function: Callable[[bytes], None]):
  712. """
  713. Compiles the input model and writes the serialized ONNX bytes to a stream using the provided write function.
  714. Raises an 'InvalidArgument' exception if the compilation options are invalid.
  715. :param write_function: A callable that accepts a bytes buffer to write.
  716. """
  717. self._model_compiler.compile_to_stream(write_function)
  718. class IOBinding:
  719. """
  720. This class provides API to bind input/output to a specified device, e.g. GPU.
  721. """
  722. def __init__(self, session: Session):
  723. self._iobinding = C.SessionIOBinding(session._sess)
  724. self._numpy_obj_references = {}
  725. def bind_cpu_input(self, name, arr_on_cpu):
  726. """
  727. bind an input to array on CPU
  728. :param name: input name
  729. :param arr_on_cpu: input values as a python array on CPU
  730. """
  731. # Hold a reference to the numpy object as the bound OrtValue is backed
  732. # directly by the data buffer of the numpy object and so the numpy object
  733. # must be around until this IOBinding instance is around
  734. self._numpy_obj_references[name] = arr_on_cpu
  735. self._iobinding.bind_input(name, arr_on_cpu)
  736. def bind_input(self, name, device_type, device_id, element_type, shape, buffer_ptr):
  737. """
  738. :param name: input name
  739. :param device_type: e.g. cpu, cuda, cann
  740. :param device_id: device id, e.g. 0
  741. :param element_type: input element type. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16)
  742. :param shape: input shape
  743. :param buffer_ptr: memory pointer to input data
  744. """
  745. self._iobinding.bind_input(
  746. name,
  747. C.OrtDevice(
  748. get_ort_device_type(device_type),
  749. C.OrtDevice.default_memory(),
  750. device_id,
  751. ),
  752. element_type,
  753. shape,
  754. buffer_ptr,
  755. )
  756. def bind_ortvalue_input(self, name, ortvalue):
  757. """
  758. :param name: input name
  759. :param ortvalue: OrtValue instance to bind
  760. """
  761. self._iobinding.bind_ortvalue_input(name, ortvalue._ortvalue)
  762. def synchronize_inputs(self):
  763. self._iobinding.synchronize_inputs()
  764. def bind_output(
  765. self,
  766. name,
  767. device_type="cpu",
  768. device_id=0,
  769. element_type=None,
  770. shape=None,
  771. buffer_ptr=None,
  772. ):
  773. """
  774. :param name: output name
  775. :param device_type: e.g. cpu, cuda, cann, cpu by default
  776. :param device_id: device id, e.g. 0
  777. :param element_type: output element type. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16)
  778. :param shape: output shape
  779. :param buffer_ptr: memory pointer to output data
  780. """
  781. # Follow the `if` path when the user has not provided any pre-allocated buffer but still
  782. # would like to bind an output to a specific device (e.g. cuda).
  783. # Pre-allocating an output buffer may not be an option for the user as :
  784. # (1) They may not want to use a custom allocator specific to the device they want to bind the output to,
  785. # in which case ORT will allocate the memory for the user
  786. # (2) The output has a dynamic shape and hence the size of the buffer may not be fixed across runs
  787. if buffer_ptr is None:
  788. self._iobinding.bind_output(
  789. name,
  790. C.OrtDevice(
  791. get_ort_device_type(device_type),
  792. C.OrtDevice.default_memory(),
  793. device_id,
  794. ),
  795. )
  796. else:
  797. if element_type is None or shape is None:
  798. raise ValueError("`element_type` and `shape` are to be provided if pre-allocated memory is provided")
  799. self._iobinding.bind_output(
  800. name,
  801. C.OrtDevice(
  802. get_ort_device_type(device_type),
  803. C.OrtDevice.default_memory(),
  804. device_id,
  805. ),
  806. element_type,
  807. shape,
  808. buffer_ptr,
  809. )
  810. def bind_ortvalue_output(self, name, ortvalue):
  811. """
  812. :param name: output name
  813. :param ortvalue: OrtValue instance to bind
  814. """
  815. self._iobinding.bind_ortvalue_output(name, ortvalue._ortvalue)
  816. def synchronize_outputs(self):
  817. self._iobinding.synchronize_outputs()
  818. def get_outputs(self):
  819. """
  820. Returns the output OrtValues from the Run() that preceded the call.
  821. The data buffer of the obtained OrtValues may not reside on CPU memory
  822. """
  823. outputs = self._iobinding.get_outputs()
  824. if not isinstance(outputs, C.OrtValueVector):
  825. raise TypeError("get_outputs() must return an instance of type 'OrtValueVector'.")
  826. return [OrtValue(ortvalue) for ortvalue in outputs]
  827. def get_outputs_as_ortvaluevector(self):
  828. return self._iobinding.get_outputs()
  829. def copy_outputs_to_cpu(self):
  830. """Copy output contents to CPU."""
  831. return self._iobinding.copy_outputs_to_cpu()
  832. def clear_binding_inputs(self):
  833. self._iobinding.clear_binding_inputs()
  834. def clear_binding_outputs(self):
  835. self._iobinding.clear_binding_outputs()
  836. class OrtValue:
  837. """
  838. A data structure that supports all ONNX data formats (tensors and non-tensors) that allows users
  839. to place the data backing these on a device, for example, on a CUDA supported device.
  840. This class provides APIs to construct and deal with OrtValues.
  841. """
  842. def __init__(self, ortvalue: C.OrtValue, numpy_obj: np.ndarray | None = None):
  843. if isinstance(ortvalue, C.OrtValue):
  844. self._ortvalue = ortvalue
  845. # Hold a ref count to the numpy object if the OrtValue is backed directly
  846. # by its data buffer so that it isn't destroyed when the OrtValue is in use
  847. self._numpy_obj = numpy_obj
  848. else:
  849. # An end user won't hit this error
  850. raise ValueError(
  851. "`Provided ortvalue` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtValue`"
  852. )
  853. def _get_c_value(self) -> C.OrtValue:
  854. return self._ortvalue
  855. @classmethod
  856. def ortvalue_from_numpy(cls, numpy_obj: np.ndarray, /, device_type="cpu", device_id=0, vendor_id=-1) -> OrtValue:
  857. """
  858. Factory method to construct an OrtValue (which holds a Tensor) from a given Numpy object
  859. A copy of the data in the Numpy object is held by the OrtValue only if the device is NOT cpu
  860. :param numpy_obj: The Numpy object to construct the OrtValue from
  861. :param device_type: e.g. cpu, cuda, cann, cpu by default
  862. :param device_id: device id, e.g. 0
  863. :param vendor_id: The device's PCI vendor id. If provided, the device_type should be "gpu" or "npu".
  864. """
  865. # Hold a reference to the numpy object (if device_type is 'cpu') as the OrtValue
  866. # is backed directly by the data buffer of the numpy object and so the numpy object
  867. # must be around until this OrtValue instance is around
  868. return cls(
  869. C.OrtValue.ortvalue_from_numpy(
  870. numpy_obj,
  871. OrtDevice.make(device_type, device_id, vendor_id)._get_c_device(),
  872. ),
  873. numpy_obj if device_type.lower() == "cpu" else None,
  874. )
  875. @classmethod
  876. def ortvalue_from_numpy_with_onnx_type(cls, data: np.ndarray, /, onnx_element_type: int) -> OrtValue:
  877. """
  878. This method creates an instance of OrtValue on top of the numpy array.
  879. No data copy is made and the lifespan of the resulting OrtValue should never
  880. exceed the lifespan of bytes object. The API attempts to reinterpret
  881. the data type which is expected to be the same size. This is useful
  882. when we want to use an ONNX data type that is not supported by numpy.
  883. :param data: numpy.ndarray.
  884. :param onnx_element_type: a valid onnx TensorProto::DataType enum value
  885. """
  886. return cls(C.OrtValue.ortvalue_from_numpy_with_onnx_type(data, onnx_element_type), data)
  887. @classmethod
  888. def ortvalue_from_shape_and_type(
  889. cls, shape: Sequence[int], element_type, device_type: str = "cpu", device_id: int = 0, vendor_id: int = -1
  890. ) -> OrtValue:
  891. """
  892. Factory method to construct an OrtValue (which holds a Tensor) from given shape and element_type
  893. :param shape: List of integers indicating the shape of the OrtValue
  894. :param element_type: The data type of the elements. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16).
  895. :param device_type: e.g. cpu, cuda, cann, cpu by default
  896. :param device_id: device id, e.g. 0
  897. :param vendor_id: If provided the device type should be "gpu" or "npu".
  898. """
  899. device = OrtDevice.make(device_type, device_id, vendor_id)._get_c_device()
  900. # Integer for onnx element type (see https://onnx.ai/onnx/api/mapping.html).
  901. # This is helpful for some data type (like TensorProto.BFLOAT16) that is not available in numpy.
  902. if isinstance(element_type, int):
  903. return cls(
  904. C.OrtValue.ortvalue_from_shape_and_onnx_type(
  905. shape,
  906. element_type,
  907. device,
  908. )
  909. )
  910. return cls(
  911. C.OrtValue.ortvalue_from_shape_and_type(
  912. shape,
  913. element_type,
  914. device,
  915. )
  916. )
  917. @classmethod
  918. def ort_value_from_sparse_tensor(cls, sparse_tensor: SparseTensor) -> OrtValue:
  919. """
  920. The function will construct an OrtValue instance from a valid SparseTensor
  921. The new instance of OrtValue will assume the ownership of sparse_tensor
  922. """
  923. return cls(C.OrtValue.ort_value_from_sparse_tensor(sparse_tensor._get_c_tensor()))
  924. def as_sparse_tensor(self) -> SparseTensor:
  925. """
  926. The function will return SparseTensor contained in this OrtValue
  927. """
  928. return SparseTensor(self._ortvalue.as_sparse_tensor())
  929. def data_ptr(self) -> int:
  930. """
  931. Returns the address of the first element in the OrtValue's data buffer
  932. """
  933. return self._ortvalue.data_ptr()
  934. def device_name(self) -> str:
  935. """
  936. Returns the name of the device where the OrtValue's data buffer resides e.g. cpu, cuda, cann
  937. """
  938. return self._ortvalue.device_name().lower()
  939. def shape(self) -> Sequence[int]:
  940. """
  941. Returns the shape of the data in the OrtValue
  942. """
  943. return self._ortvalue.shape()
  944. def data_type(self) -> str:
  945. """
  946. Returns the data type of the data in the OrtValue. E.g. 'tensor(int64)'
  947. """
  948. return self._ortvalue.data_type()
  949. def element_type(self) -> int:
  950. """
  951. Returns the proto type of the data in the OrtValue
  952. if the OrtValue is a tensor.
  953. """
  954. return self._ortvalue.element_type()
  955. def tensor_size_in_bytes(self) -> int:
  956. """
  957. Returns the size of the data in the OrtValue in bytes
  958. if the OrtValue is a tensor.
  959. """
  960. return self._ortvalue.tensor_size_in_bytes()
  961. def has_value(self) -> bool:
  962. """
  963. Returns True if the OrtValue corresponding to an
  964. optional type contains data, else returns False
  965. """
  966. return self._ortvalue.has_value()
  967. def is_tensor(self) -> bool:
  968. """
  969. Returns True if the OrtValue contains a Tensor, else returns False
  970. """
  971. return self._ortvalue.is_tensor()
  972. def is_sparse_tensor(self) -> bool:
  973. """
  974. Returns True if the OrtValue contains a SparseTensor, else returns False
  975. """
  976. return self._ortvalue.is_sparse_tensor()
  977. def is_tensor_sequence(self) -> bool:
  978. """
  979. Returns True if the OrtValue contains a Tensor Sequence, else returns False
  980. """
  981. return self._ortvalue.is_tensor_sequence()
  982. def numpy(self) -> np.ndarray:
  983. """
  984. Returns a Numpy object from the OrtValue.
  985. Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
  986. Use accessors to gain a reference to non-Tensor objects such as SparseTensor
  987. """
  988. return self._ortvalue.numpy()
  989. def update_inplace(self, np_arr) -> None:
  990. """
  991. Update the OrtValue in place with a new Numpy array. The numpy contents
  992. are copied over to the device memory backing the OrtValue. It can be used
  993. to update the input valuess for an InferenceSession with CUDA graph
  994. enabled or other scenarios where the OrtValue needs to be updated while
  995. the memory address can not be changed.
  996. """
  997. self._ortvalue.update_inplace(np_arr)
  998. def copy_tensors(src: Sequence[OrtValue], dst: Sequence[OrtValue], stream=None) -> None:
  999. """
  1000. Copy tensor data from source OrtValue sequence to destination OrtValue sequence.
  1001. """
  1002. c_sources = [s._get_c_value() for s in src]
  1003. c_dsts = [d._get_c_value() for d in dst]
  1004. C.copy_tensors(c_sources, c_dsts, stream)
  1005. class OrtDevice:
  1006. """
  1007. A data structure that exposes the underlying C++ OrtDevice
  1008. """
  1009. def __init__(self, c_ort_device):
  1010. """
  1011. Internal constructor
  1012. """
  1013. if isinstance(c_ort_device, C.OrtDevice):
  1014. self._ort_device = c_ort_device
  1015. else:
  1016. # An end user won't hit this error
  1017. raise ValueError(
  1018. "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtDevice`"
  1019. )
  1020. def _get_c_device(self):
  1021. """
  1022. Internal accessor to underlying object
  1023. """
  1024. return self._ort_device
  1025. @staticmethod
  1026. def make(ort_device_name, device_id, vendor_id=-1):
  1027. if vendor_id < 0:
  1028. # backwards compatibility with predefined OrtDevice names
  1029. return OrtDevice(
  1030. C.OrtDevice(
  1031. get_ort_device_type(ort_device_name),
  1032. C.OrtDevice.default_memory(),
  1033. device_id,
  1034. )
  1035. )
  1036. else:
  1037. # generic. use GPU or NPU for ort_device_name and provide a vendor id.
  1038. # vendor id of 0 is valid in some cases (e.g. webgpu is generic and does not have a vendor id)
  1039. return OrtDevice(
  1040. C.OrtDevice(
  1041. get_ort_device_type(ort_device_name),
  1042. C.OrtDevice.default_memory(),
  1043. vendor_id,
  1044. device_id,
  1045. )
  1046. )
  1047. def device_id(self):
  1048. return self._ort_device.device_id()
  1049. def device_type(self):
  1050. return self._ort_device.device_type()
  1051. def device_vendor_id(self):
  1052. return self._ort_device.vendor_id()
  1053. def device_mem_type(self):
  1054. return self._ort_device.mem_type()
  1055. class SparseTensor:
  1056. """
  1057. A data structure that project the C++ SparseTensor object
  1058. The class provides API to work with the object.
  1059. Depending on the format, the class will hold more than one buffer
  1060. depending on the format
  1061. """
  1062. def __init__(self, sparse_tensor: C.SparseTensor):
  1063. """
  1064. Internal constructor
  1065. """
  1066. if isinstance(sparse_tensor, C.SparseTensor):
  1067. self._tensor = sparse_tensor
  1068. else:
  1069. # An end user won't hit this error
  1070. raise ValueError(
  1071. "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.SparseTensor`"
  1072. )
  1073. def _get_c_tensor(self) -> C.SparseTensor:
  1074. return self._tensor
  1075. @classmethod
  1076. def sparse_coo_from_numpy(
  1077. cls,
  1078. dense_shape: npt.NDArray[np.int64],
  1079. values: np.ndarray,
  1080. coo_indices: npt.NDArray[np.int64],
  1081. ort_device: OrtDevice,
  1082. ) -> SparseTensor:
  1083. """
  1084. Factory method to construct a SparseTensor in COO format from given arguments
  1085. :param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor
  1086. must be on cpu memory
  1087. :param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor
  1088. of a type.
  1089. :param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may
  1090. have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to
  1091. that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for
  1092. each of the nnz values and its length must be exactly twice of the values length.
  1093. :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
  1094. suppored for non-numeric data types.
  1095. For primitive types, the method will map values and coo_indices arrays into native memory and will use
  1096. them as backing storage. It will increment the reference count for numpy arrays and it will decrement it
  1097. on GC. The buffers may reside in any storage either CPU or GPU.
  1098. For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
  1099. on other devices and their memory can not be mapped.
  1100. """
  1101. return cls(C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device._get_c_device()))
  1102. @classmethod
  1103. def sparse_csr_from_numpy(
  1104. cls,
  1105. dense_shape: npt.NDArray[np.int64],
  1106. values: np.ndarray,
  1107. inner_indices: npt.NDArray[np.int64],
  1108. outer_indices: npt.NDArray[np.int64],
  1109. ort_device: OrtDevice,
  1110. ) -> SparseTensor:
  1111. """
  1112. Factory method to construct a SparseTensor in CSR format from given arguments
  1113. :param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the
  1114. sparse tensor (rows, cols) must be on cpu memory
  1115. :param values: a contiguous, homogeneous 1-D numpy array that contains non-zero elements of the tensor
  1116. of a type.
  1117. :param inner_indices: contiguous 1-D numpy array(int64) that contains CSR inner indices for the tensor.
  1118. Its length must be equal to that of the values.
  1119. :param outer_indices: contiguous 1-D numpy array(int64) that contains CSR outer indices for the tensor.
  1120. Its length must be equal to the number of rows + 1.
  1121. :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
  1122. suppored for non-numeric data types.
  1123. For primitive types, the method will map values and indices arrays into native memory and will use them as
  1124. backing storage. It will increment the reference count and it will decrement then count when it is GCed.
  1125. The buffers may reside in any storage either CPU or GPU.
  1126. For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
  1127. on other devices and their memory can not be mapped.
  1128. """
  1129. return cls(
  1130. C.SparseTensor.sparse_csr_from_numpy(
  1131. dense_shape,
  1132. values,
  1133. inner_indices,
  1134. outer_indices,
  1135. ort_device._get_c_device(),
  1136. )
  1137. )
  1138. def values(self) -> np.ndarray:
  1139. """
  1140. The method returns a numpy array that is backed by the native memory
  1141. if the data type is numeric. Otherwise, the returned numpy array that contains
  1142. copies of the strings.
  1143. """
  1144. return self._tensor.values()
  1145. def as_coo_view(self):
  1146. """
  1147. The method will return coo representation of the sparse tensor which will enable
  1148. querying COO indices. If the instance did not contain COO format, it would throw.
  1149. You can query coo indices as:
  1150. ::
  1151. coo_indices = sparse_tensor.as_coo_view().indices()
  1152. which will return a numpy array that is backed by the native memory.
  1153. """
  1154. return self._tensor.get_coo_data()
  1155. def as_csrc_view(self):
  1156. """
  1157. The method will return CSR(C) representation of the sparse tensor which will enable
  1158. querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw.
  1159. You can query indices as:
  1160. ::
  1161. inner_ndices = sparse_tensor.as_csrc_view().inner()
  1162. outer_ndices = sparse_tensor.as_csrc_view().outer()
  1163. returning numpy arrays backed by the native memory.
  1164. """
  1165. return self._tensor.get_csrc_data()
  1166. def as_blocksparse_view(self):
  1167. """
  1168. The method will return coo representation of the sparse tensor which will enable
  1169. querying BlockSparse indices. If the instance did not contain BlockSparse format, it would throw.
  1170. You can query coo indices as:
  1171. ::
  1172. block_sparse_indices = sparse_tensor.as_blocksparse_view().indices()
  1173. which will return a numpy array that is backed by the native memory
  1174. """
  1175. return self._tensor.get_blocksparse_data()
  1176. def to_cuda(self, ort_device):
  1177. """
  1178. Returns a copy of this instance on the specified cuda device
  1179. :param ort_device: with name 'cuda' and valid gpu device id
  1180. The method will throw if:
  1181. - this instance contains strings
  1182. - this instance is already on GPU. Cross GPU copy is not supported
  1183. - CUDA is not present in this build
  1184. - if the specified device is not valid
  1185. """
  1186. return SparseTensor(self._tensor.to_cuda(ort_device._get_c_device()))
  1187. def format(self):
  1188. """
  1189. Returns a OrtSparseFormat enumeration
  1190. """
  1191. return self._tensor.format
  1192. def dense_shape(self) -> npt.NDArray[np.int64]:
  1193. """
  1194. Returns a numpy array(int64) containing a dense shape of a sparse tensor
  1195. """
  1196. return self._tensor.dense_shape()
  1197. def data_type(self) -> str:
  1198. """
  1199. Returns a string data type of the data in the OrtValue
  1200. """
  1201. return self._tensor.data_type()
  1202. def device_name(self) -> str:
  1203. """
  1204. Returns the name of the device where the SparseTensor data buffers reside e.g. cpu, cuda
  1205. """
  1206. return self._tensor.device_name().lower()
  1207. # Type hint for user-specified function that allows the user to specify initializer locations when compiling a model.
  1208. GetInitializerLocationFunc = Callable[
  1209. [str, OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None
  1210. ]
  1211. # Type hint that adheres to the signature expected by ORT.
  1212. GetInitializerLocationWrapperFunc = Callable[
  1213. [str, C.OrtValue, C.OrtExternalInitializerInfo | None], C.OrtExternalInitializerInfo | None
  1214. ]