hpi.py 10 KB

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