__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License.
  4. # --------------------------------------------------------------------------
  5. """
  6. ONNX Runtime is a performance-focused scoring engine for Open Neural Network Exchange (ONNX) models.
  7. For more information on ONNX Runtime, please see `aka.ms/onnxruntime <https://aka.ms/onnxruntime/>`_
  8. or the `Github project <https://github.com/microsoft/onnxruntime/>`_.
  9. """
  10. __version__ = "1.23.2"
  11. __author__ = "Microsoft"
  12. # we need to do device version validation (for example to check Cuda version for an onnxruntime-training package).
  13. # in order to know whether the onnxruntime package is for training it needs
  14. # to do import onnxruntime.training.ortmodule first.
  15. # onnxruntime.capi._pybind_state is required before import onnxruntime.training.ortmodule.
  16. # however, import onnxruntime.capi._pybind_state will already raise an exception if a required Cuda version
  17. # is not found.
  18. # here we need to save the exception and continue with Cuda version validation in order to post
  19. # meaningful messages to the user.
  20. # the saved exception is raised after device version validation.
  21. try:
  22. from onnxruntime.capi._pybind_state import (
  23. ExecutionMode, # noqa: F401
  24. ExecutionOrder, # noqa: F401
  25. GraphOptimizationLevel, # noqa: F401
  26. LoraAdapter, # noqa: F401
  27. ModelMetadata, # noqa: F401
  28. NodeArg, # noqa: F401
  29. OrtAllocatorType, # noqa: F401
  30. OrtArenaCfg, # noqa: F401
  31. OrtCompileApiFlags, # noqa: F401
  32. OrtDeviceMemoryType, # noqa: F401
  33. OrtEpDevice, # noqa: F401
  34. OrtExecutionProviderDevicePolicy, # noqa: F401
  35. OrtExternalInitializerInfo, # noqa: F401
  36. OrtHardwareDevice, # noqa: F401
  37. OrtHardwareDeviceType, # noqa: F401
  38. OrtMemoryInfo, # noqa: F401
  39. OrtMemoryInfoDeviceType, # noqa: F401
  40. OrtMemType, # noqa: F401
  41. OrtSparseFormat, # noqa: F401
  42. OrtSyncStream, # noqa: F401
  43. RunOptions, # noqa: F401
  44. SessionIOBinding, # noqa: F401
  45. SessionOptions, # noqa: F401
  46. create_and_register_allocator, # noqa: F401
  47. create_and_register_allocator_v2, # noqa: F401
  48. disable_telemetry_events, # noqa: F401
  49. enable_telemetry_events, # noqa: F401
  50. get_all_providers, # noqa: F401
  51. get_available_providers, # noqa: F401
  52. get_build_info, # noqa: F401
  53. get_device, # noqa: F401
  54. get_ep_devices, # noqa: F401
  55. get_version_string, # noqa: F401
  56. has_collective_ops, # noqa: F401
  57. register_execution_provider_library, # noqa: F401
  58. set_default_logger_severity, # noqa: F401
  59. set_default_logger_verbosity, # noqa: F401
  60. set_global_thread_pool_sizes, # noqa: F401
  61. set_seed, # noqa: F401
  62. unregister_execution_provider_library, # noqa: F401
  63. )
  64. import_capi_exception = None
  65. except Exception as e:
  66. import_capi_exception = e
  67. from onnxruntime.capi import onnxruntime_validation
  68. if import_capi_exception:
  69. raise import_capi_exception
  70. from onnxruntime.capi.onnxruntime_inference_collection import (
  71. AdapterFormat, # noqa: F401
  72. InferenceSession, # noqa: F401
  73. IOBinding, # noqa: F401
  74. ModelCompiler, # noqa: F401
  75. OrtDevice, # noqa: F401
  76. OrtValue, # noqa: F401
  77. SparseTensor, # noqa: F401
  78. copy_tensors, # noqa: F401
  79. )
  80. # TODO: thiagofc: Temporary experimental namespace for new PyTorch front-end
  81. try: # noqa: SIM105
  82. from . import experimental # noqa: F401
  83. except ImportError:
  84. pass
  85. package_name, version, cuda_version = onnxruntime_validation.get_package_name_and_version_info()
  86. if version:
  87. __version__ = version
  88. onnxruntime_validation.check_distro_info()
  89. def _get_package_version(package_name: str):
  90. from importlib.metadata import PackageNotFoundError, version # noqa: PLC0415
  91. try:
  92. package_version = version(package_name)
  93. except PackageNotFoundError:
  94. package_version = None
  95. return package_version
  96. def _get_package_root(package_name: str, directory_name: str | None = None):
  97. from importlib.metadata import PackageNotFoundError, distribution # noqa: PLC0415
  98. root_directory_name = directory_name or package_name
  99. try:
  100. dist = distribution(package_name)
  101. files = dist.files or []
  102. for file in files:
  103. if file.name.endswith("__init__.py") and root_directory_name in file.parts:
  104. return file.locate().parent
  105. # Fallback to the first __init__.py
  106. if not directory_name:
  107. for file in files:
  108. if file.name.endswith("__init__.py"):
  109. return file.locate().parent
  110. except PackageNotFoundError:
  111. # package not found, do nothing
  112. pass
  113. return None
  114. def _get_nvidia_dll_paths(is_windows: bool, cuda: bool = True, cudnn: bool = True):
  115. if is_windows:
  116. # Path is relative to site-packages directory.
  117. cuda_dll_paths = [
  118. ("nvidia", "cublas", "bin", "cublasLt64_12.dll"),
  119. ("nvidia", "cublas", "bin", "cublas64_12.dll"),
  120. ("nvidia", "cufft", "bin", "cufft64_11.dll"),
  121. ("nvidia", "cuda_runtime", "bin", "cudart64_12.dll"),
  122. ]
  123. cudnn_dll_paths = [
  124. ("nvidia", "cudnn", "bin", "cudnn_engines_runtime_compiled64_9.dll"),
  125. ("nvidia", "cudnn", "bin", "cudnn_engines_precompiled64_9.dll"),
  126. ("nvidia", "cudnn", "bin", "cudnn_heuristic64_9.dll"),
  127. ("nvidia", "cudnn", "bin", "cudnn_ops64_9.dll"),
  128. ("nvidia", "cudnn", "bin", "cudnn_adv64_9.dll"),
  129. ("nvidia", "cudnn", "bin", "cudnn_graph64_9.dll"),
  130. ("nvidia", "cudnn", "bin", "cudnn64_9.dll"),
  131. ]
  132. else: # Linux
  133. # cublas64 depends on cublasLt64, so cublasLt64 should be loaded first.
  134. cuda_dll_paths = [
  135. ("nvidia", "cublas", "lib", "libcublasLt.so.12"),
  136. ("nvidia", "cublas", "lib", "libcublas.so.12"),
  137. ("nvidia", "cuda_nvrtc", "lib", "libnvrtc.so.12"),
  138. ("nvidia", "curand", "lib", "libcurand.so.10"),
  139. ("nvidia", "cufft", "lib", "libcufft.so.11"),
  140. ("nvidia", "cuda_runtime", "lib", "libcudart.so.12"),
  141. ]
  142. # Do not load cudnn sub DLLs (they will be dynamically loaded later) to be consistent with PyTorch in Linux.
  143. cudnn_dll_paths = [
  144. ("nvidia", "cudnn", "lib", "libcudnn.so.9"),
  145. ]
  146. return (cuda_dll_paths if cuda else []) + (cudnn_dll_paths if cudnn else [])
  147. def print_debug_info():
  148. """Print information to help debugging."""
  149. import importlib.util # noqa: PLC0415
  150. import os # noqa: PLC0415
  151. import platform # noqa: PLC0415
  152. from importlib.metadata import distributions # noqa: PLC0415
  153. print(f"{package_name} version: {__version__}")
  154. if cuda_version:
  155. print(f"CUDA version used in build: {cuda_version}")
  156. print("platform:", platform.platform())
  157. print("\nPython package, version and location:")
  158. ort_packages = []
  159. for dist in distributions():
  160. package = dist.metadata["Name"]
  161. if package == "onnxruntime" or package.startswith(("onnxruntime-", "ort-")):
  162. # Exclude packages whose root directory name is not onnxruntime.
  163. location = _get_package_root(package, "onnxruntime")
  164. if location and (package not in ort_packages):
  165. ort_packages.append(package)
  166. print(f"{package}=={dist.version} at {location}")
  167. if len(ort_packages) > 1:
  168. print(
  169. "\033[33mWARNING: multiple onnxruntime packages are installed to the same location. "
  170. "Please 'pip uninstall` all above packages, then `pip install` only one of them.\033[0m"
  171. )
  172. if cuda_version:
  173. # Print version of installed packages that is related to CUDA or cuDNN DLLs.
  174. packages = [
  175. "torch",
  176. "nvidia-cuda-runtime-cu12",
  177. "nvidia-cudnn-cu12",
  178. "nvidia-cublas-cu12",
  179. "nvidia-cufft-cu12",
  180. "nvidia-curand-cu12",
  181. "nvidia-cuda-nvrtc-cu12",
  182. "nvidia-nvjitlink-cu12",
  183. ]
  184. for package in packages:
  185. directory_name = "nvidia" if package.startswith("nvidia-") else None
  186. version = _get_package_version(package)
  187. if version:
  188. print(f"{package}=={version} at {_get_package_root(package, directory_name)}")
  189. else:
  190. print(f"{package} not installed")
  191. if platform.system() == "Windows":
  192. print(f"\nEnvironment variable:\nPATH={os.environ['PATH']}")
  193. elif platform.system() == "Linux":
  194. print(f"\nEnvironment variable:\nLD_LIBRARY_PATH={os.environ['LD_LIBRARY_PATH']}")
  195. if importlib.util.find_spec("psutil"):
  196. def is_target_dll(path: str):
  197. target_keywords = ["vcruntime140", "msvcp140"]
  198. if cuda_version:
  199. target_keywords = ["cufft", "cublas", "cudart", "nvrtc", "curand", "cudnn", *target_keywords]
  200. return any(keyword in path for keyword in target_keywords)
  201. import psutil # noqa: PLC0415
  202. p = psutil.Process(os.getpid())
  203. print("\nList of loaded DLLs:")
  204. for lib in p.memory_maps():
  205. if is_target_dll(lib.path.lower()):
  206. print(lib.path)
  207. if cuda_version:
  208. if importlib.util.find_spec("cpuinfo") and importlib.util.find_spec("py3nvml"):
  209. from .transformers.machine_info import get_device_info # noqa: PLC0415
  210. print("\nDevice information:")
  211. print(get_device_info())
  212. else:
  213. print("please `pip install py-cpuinfo py3nvml` to show device information.")
  214. else:
  215. print("please `pip install psutil` to show loaded DLLs.")
  216. def preload_dlls(cuda: bool = True, cudnn: bool = True, msvc: bool = True, directory=None):
  217. """Preload CUDA 12.x and cuDNN 9.x DLLs in Windows or Linux, and MSVC runtime DLLs in Windows.
  218. When the installed PyTorch is compatible (using same major version of CUDA and cuDNN),
  219. there is no need to call this function if `import torch` is done before `import onnxruntime`.
  220. Args:
  221. cuda (bool, optional): enable loading CUDA DLLs. Defaults to True.
  222. cudnn (bool, optional): enable loading cuDNN DLLs. Defaults to True.
  223. msvc (bool, optional): enable loading MSVC DLLs in Windows. Defaults to True.
  224. directory(str, optional): a directory contains CUDA or cuDNN DLLs. It can be an absolute path,
  225. or a path relative to the directory of this file.
  226. If directory is None (default value), the search order: the lib directory of compatible PyTorch in Windows,
  227. nvidia site packages, default DLL loading paths.
  228. If directory is empty string (""), the search order: nvidia site packages, default DLL loading paths.
  229. If directory is a path, the search order: the directory, default DLL loading paths.
  230. """
  231. import ctypes # noqa: PLC0415
  232. import os # noqa: PLC0415
  233. import platform # noqa: PLC0415
  234. import sys # noqa: PLC0415
  235. if platform.system() not in ["Windows", "Linux"]:
  236. return
  237. is_windows = platform.system() == "Windows"
  238. if is_windows and msvc:
  239. try:
  240. ctypes.CDLL("vcruntime140.dll")
  241. ctypes.CDLL("msvcp140.dll")
  242. if platform.machine() != "ARM64":
  243. ctypes.CDLL("vcruntime140_1.dll")
  244. except OSError:
  245. print("Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.")
  246. print("It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe.")
  247. if not (cuda_version and cuda_version.startswith("12.")) and (cuda or cudnn):
  248. print(
  249. f"\033[33mWARNING: {package_name} is not built with CUDA 12.x support. "
  250. "Please install a version that supports CUDA 12.x, or call preload_dlls with cuda=False and cudnn=False.\033[0m"
  251. )
  252. return
  253. if not (cuda_version and cuda_version.startswith("12.") and (cuda or cudnn)):
  254. return
  255. is_cuda_cudnn_imported_by_torch = False
  256. if is_windows:
  257. torch_version = _get_package_version("torch")
  258. is_torch_for_cuda_12 = torch_version and "+cu12" in torch_version
  259. if "torch" in sys.modules:
  260. is_cuda_cudnn_imported_by_torch = is_torch_for_cuda_12
  261. if (torch_version and "+cu" in torch_version) and not is_torch_for_cuda_12:
  262. print(
  263. f"\033[33mWARNING: The installed PyTorch {torch_version} does not support CUDA 12.x. "
  264. f"Please install PyTorch for CUDA 12.x to be compatible with {package_name}.\033[0m"
  265. )
  266. if is_torch_for_cuda_12 and directory is None:
  267. torch_root = _get_package_root("torch", "torch")
  268. if torch_root:
  269. directory = os.path.join(torch_root, "lib")
  270. base_directory = directory or ".."
  271. if not os.path.isabs(base_directory):
  272. base_directory = os.path.join(os.path.dirname(__file__), base_directory)
  273. base_directory = os.path.normpath(base_directory)
  274. if not os.path.isdir(base_directory):
  275. raise RuntimeError(f"Invalid parameter of directory={directory}. The directory does not exist!")
  276. if is_cuda_cudnn_imported_by_torch:
  277. # In Windows, PyTorch has loaded CUDA and cuDNN DLLs during `import torch`, no need to load them again.
  278. print("Skip loading CUDA and cuDNN DLLs since torch is imported.")
  279. return
  280. # Try load DLLs from nvidia site packages.
  281. dll_paths = _get_nvidia_dll_paths(is_windows, cuda, cudnn)
  282. loaded_dlls = []
  283. for relative_path in dll_paths:
  284. dll_path = (
  285. os.path.join(base_directory, relative_path[-1])
  286. if directory
  287. else os.path.join(base_directory, *relative_path)
  288. )
  289. if os.path.isfile(dll_path):
  290. try:
  291. _ = ctypes.CDLL(dll_path)
  292. loaded_dlls.append(relative_path[-1])
  293. except Exception as e:
  294. print(f"Failed to load {dll_path}: {e}")
  295. # Try load DLLs with default path settings.
  296. has_failure = False
  297. for relative_path in dll_paths:
  298. dll_filename = relative_path[-1]
  299. if dll_filename not in loaded_dlls:
  300. try:
  301. _ = ctypes.CDLL(dll_filename)
  302. except Exception as e:
  303. has_failure = True
  304. print(f"Failed to load {dll_filename}: {e}")
  305. if has_failure:
  306. print("Please follow https://onnxruntime.ai/docs/install/#cuda-and-cudnn to install CUDA and CuDNN.")