hpi.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import ctypes.util
  15. import importlib.resources
  16. import importlib.util
  17. import json
  18. import platform
  19. from collections import defaultdict
  20. from functools import lru_cache
  21. from typing import Any, Dict, List, Literal, Optional, Tuple, Union
  22. from pydantic import BaseModel, Field
  23. from typing_extensions import Annotated, TypeAlias
  24. from ...utils.deps import function_requires_deps, is_paddle2onnx_plugin_available
  25. from ...utils.env import (
  26. get_paddle_cuda_version,
  27. get_paddle_cudnn_version,
  28. get_paddle_version,
  29. )
  30. from ...utils.flags import USE_PIR_TRT
  31. from .misc import is_mkldnn_available
  32. from .model_paths import ModelPaths
  33. class PaddleInferenceInfo(BaseModel):
  34. trt_dynamic_shapes: Optional[Dict[str, List[List[int]]]] = None
  35. trt_dynamic_shape_input_data: Optional[Dict[str, List[List[float]]]] = None
  36. class TensorRTInfo(BaseModel):
  37. dynamic_shapes: Optional[Dict[str, List[List[int]]]] = None
  38. class InferenceBackendInfoCollection(BaseModel):
  39. paddle_infer: Optional[PaddleInferenceInfo] = None
  40. tensorrt: Optional[TensorRTInfo] = None
  41. # Does using `TypedDict` make things more convenient?
  42. class HPIInfo(BaseModel):
  43. backend_configs: Optional[InferenceBackendInfoCollection] = None
  44. # For multi-backend inference only
  45. InferenceBackend: TypeAlias = Literal[
  46. "paddle", "openvino", "onnxruntime", "tensorrt", "om"
  47. ]
  48. class OpenVINOConfig(BaseModel):
  49. cpu_num_threads: int = 8
  50. class ONNXRuntimeConfig(BaseModel):
  51. cpu_num_threads: int = 8
  52. class TensorRTConfig(BaseModel):
  53. precision: Literal["fp32", "fp16"] = "fp32"
  54. use_dynamic_shapes: bool = True
  55. dynamic_shapes: Optional[Dict[str, List[List[int]]]] = None
  56. # TODO: Control caching behavior
  57. class OMConfig(BaseModel):
  58. pass
  59. class HPIConfig(BaseModel):
  60. pdx_model_name: Annotated[str, Field(alias="model_name")]
  61. device_type: str
  62. device_id: Optional[int] = None
  63. auto_config: bool = True
  64. backend: Optional[InferenceBackend] = None
  65. backend_config: Optional[Dict[str, Any]] = None
  66. hpi_info: Optional[HPIInfo] = None
  67. auto_paddle2onnx: bool = True
  68. # TODO: Add more validation logic here
  69. class ModelInfo(BaseModel):
  70. name: str
  71. hpi_info: Optional[HPIInfo] = None
  72. ModelFormat: TypeAlias = Literal["paddle", "onnx", "om"]
  73. @lru_cache(1)
  74. def _get_hpi_model_info_collection():
  75. with importlib.resources.open_text(
  76. __package__, "hpi_model_info_collection.json", encoding="utf-8"
  77. ) as f:
  78. hpi_model_info_collection = json.load(f)
  79. return hpi_model_info_collection
  80. @function_requires_deps("ultra-infer")
  81. def suggest_inference_backend_and_config(
  82. hpi_config: HPIConfig,
  83. model_paths: ModelPaths,
  84. ) -> Union[Tuple[InferenceBackend, Dict[str, Any]], Tuple[None, str]]:
  85. # TODO: The current strategy is naive. It would be better to consider
  86. # additional important factors, such as NVIDIA GPU compute capability and
  87. # device manufacturers. We should also allow users to provide hints.
  88. from ultra_infer import (
  89. is_built_with_om,
  90. is_built_with_openvino,
  91. is_built_with_ort,
  92. is_built_with_trt,
  93. )
  94. is_onnx_model_available = "onnx" in model_paths
  95. # TODO: Give a warning if the Paddle2ONNX plugin is not available but
  96. # can be used to select a better backend.
  97. if hpi_config.auto_paddle2onnx and is_paddle2onnx_plugin_available():
  98. is_onnx_model_available = is_onnx_model_available or "paddle" in model_paths
  99. available_backends = []
  100. if "paddle" in model_paths:
  101. available_backends.append("paddle")
  102. if (
  103. is_built_with_openvino()
  104. and is_onnx_model_available
  105. and hpi_config.device_type == "cpu"
  106. ):
  107. available_backends.append("openvino")
  108. if (
  109. is_built_with_ort()
  110. and is_onnx_model_available
  111. and hpi_config.device_type in ("cpu", "gpu")
  112. ):
  113. available_backends.append("onnxruntime")
  114. if (
  115. is_built_with_trt()
  116. and is_onnx_model_available
  117. and hpi_config.device_type == "gpu"
  118. ):
  119. available_backends.append("tensorrt")
  120. if is_built_with_om() and "om" in model_paths and hpi_config.device_type == "npu":
  121. available_backends.append("om")
  122. if not available_backends:
  123. return None, "No inference backends are available."
  124. if hpi_config.backend is not None and hpi_config.backend not in available_backends:
  125. return None, f"Inference backend {repr(hpi_config.backend)} is unavailable."
  126. paddle_version = get_paddle_version()
  127. if paddle_version != (3, 0, 0, None):
  128. return (
  129. None,
  130. f"{paddle_version} is not a supported Paddle version.",
  131. )
  132. if hpi_config.device_type == "cpu":
  133. uname = platform.uname()
  134. arch = uname.machine.lower()
  135. if arch == "x86_64":
  136. key = "cpu_x64"
  137. else:
  138. return None, f"{repr(arch)} is not a supported architecture."
  139. elif hpi_config.device_type == "gpu":
  140. # TODO: Is it better to also check the runtime versions of CUDA and
  141. # cuDNN, and the versions of CUDA and cuDNN used to build `ultra-infer`?
  142. cuda_version = get_paddle_cuda_version()
  143. if not cuda_version:
  144. return None, "No CUDA version was found."
  145. cuda_version = "".join(map(str, cuda_version))
  146. cudnn_version = get_paddle_cudnn_version()
  147. if not cudnn_version:
  148. return None, "No cuDNN version was found."
  149. cudnn_version = "".join(map(str, cudnn_version[:-1]))
  150. key = f"gpu_cuda{cuda_version}_cudnn{cudnn_version}"
  151. else:
  152. return None, f"{repr(hpi_config.device_type)} is not a supported device type."
  153. hpi_model_info_collection = _get_hpi_model_info_collection()
  154. if key not in hpi_model_info_collection:
  155. return None, "No prior knowledge can be utilized."
  156. hpi_model_info_collection_for_env = hpi_model_info_collection[key]
  157. if hpi_config.pdx_model_name not in hpi_model_info_collection_for_env:
  158. return None, f"{repr(hpi_config.pdx_model_name)} is not a known model."
  159. supported_pseudo_backends = hpi_model_info_collection_for_env[
  160. hpi_config.pdx_model_name
  161. ].copy()
  162. if not (is_mkldnn_available() and hpi_config.device_type == "cpu"):
  163. for pb in supported_pseudo_backends[:]:
  164. if pb.startswith("paddle_mkldnn"):
  165. supported_pseudo_backends.remove(pb)
  166. # XXX
  167. if not (
  168. USE_PIR_TRT
  169. and importlib.util.find_spec("tensorrt")
  170. and ctypes.util.find_library("nvinfer")
  171. and hpi_config.device_type == "gpu"
  172. ):
  173. for pb in supported_pseudo_backends[:]:
  174. if pb.startswith("paddle_tensorrt"):
  175. supported_pseudo_backends.remove(pb)
  176. supported_backends = []
  177. backend_to_pseudo_backends = defaultdict(list)
  178. for pb in supported_pseudo_backends:
  179. if pb.startswith("paddle"):
  180. backend = "paddle"
  181. elif pb.startswith("tensorrt"):
  182. backend = "tensorrt"
  183. else:
  184. backend = pb
  185. if available_backends is not None and backend not in available_backends:
  186. continue
  187. supported_backends.append(backend)
  188. backend_to_pseudo_backends[backend].append(pb)
  189. if not supported_backends:
  190. return None, "No inference backend can be selected."
  191. if hpi_config.backend is not None:
  192. if hpi_config.backend not in supported_backends:
  193. return (
  194. None,
  195. f"{repr(hpi_config.backend)} is not a supported inference backend.",
  196. )
  197. suggested_backend = hpi_config.backend
  198. else:
  199. # Prefer the first one.
  200. suggested_backend = supported_backends[0]
  201. pseudo_backends = backend_to_pseudo_backends[suggested_backend]
  202. if hpi_config.backend_config is not None:
  203. requested_base_pseudo_backend = None
  204. if suggested_backend == "paddle":
  205. if "run_mode" in hpi_config.backend_config:
  206. if hpi_config.backend_config["run_mode"].startswith("mkldnn"):
  207. requested_base_pseudo_backend = "paddle_mkldnn"
  208. elif hpi_config.backend_config["run_mode"].startswith("trt"):
  209. requested_base_pseudo_backend = "paddle_tensorrt"
  210. if requested_base_pseudo_backend:
  211. for pb in pseudo_backends:
  212. if pb.startswith(requested_base_pseudo_backend):
  213. break
  214. else:
  215. return None, "Unsupported backend configuration."
  216. pseudo_backend = pseudo_backends[0]
  217. suggested_backend_config = {}
  218. if suggested_backend == "paddle":
  219. assert pseudo_backend in (
  220. "paddle",
  221. "paddle_fp16",
  222. "paddle_mkldnn",
  223. "paddle_tensorrt",
  224. "paddle_tensorrt_fp16",
  225. ), pseudo_backend
  226. if pseudo_backend == "paddle":
  227. suggested_backend_config.update({"run_mode": "paddle"})
  228. elif pseudo_backend == "paddle_fp16":
  229. suggested_backend_config.update({"run_mode": "paddle_fp16"})
  230. elif pseudo_backend == "paddle_mkldnn":
  231. suggested_backend_config.update({"run_mode": "mkldnn"})
  232. elif pseudo_backend == "paddle_tensorrt":
  233. suggested_backend_config.update({"run_mode": "trt_fp32"})
  234. elif pseudo_backend == "paddle_tensorrt_fp16":
  235. # TODO: Check if the target device supports FP16.
  236. suggested_backend_config.update({"run_mode": "trt_fp16"})
  237. elif suggested_backend == "tensorrt":
  238. assert pseudo_backend in ("tensorrt", "tensorrt_fp16"), pseudo_backend
  239. if pseudo_backend == "tensorrt_fp16":
  240. suggested_backend_config.update({"precision": "fp16"})
  241. if hpi_config.backend_config is not None:
  242. suggested_backend_config.update(hpi_config.backend_config)
  243. return suggested_backend, suggested_backend_config