hpi.py 9.2 KB

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