hpi.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. cuda_version = "".join(map(str, cuda_version))
  130. cudnn_version = get_paddle_cudnn_version()
  131. cudnn_version = "".join(map(str, cudnn_version[:-1]))
  132. key = f"gpu_cuda{cuda_version}_cudnn{cudnn_version}"
  133. else:
  134. return None, f"{repr(hpi_config.device_type)} is not a supported device type."
  135. hpi_model_info_collection = _get_hpi_model_info_collection()
  136. if key not in hpi_model_info_collection:
  137. return None, "No prior knowledge can be utilized."
  138. hpi_model_info_collection_for_env = hpi_model_info_collection[key]
  139. if hpi_config.pdx_model_name not in hpi_model_info_collection_for_env:
  140. return None, f"{repr(hpi_config.pdx_model_name)} is not a known model."
  141. supported_pseudo_backends = hpi_model_info_collection_for_env[
  142. hpi_config.pdx_model_name
  143. ].copy()
  144. # XXX
  145. if not (
  146. USE_PIR_TRT
  147. and importlib.util.find_spec("tensorrt")
  148. and ctypes.util.find_library("nvinfer")
  149. ):
  150. if (
  151. "paddle_tensorrt" in supported_pseudo_backends
  152. or "paddle_tensorrt_fp16" in supported_pseudo_backends
  153. ):
  154. supported_pseudo_backends.append("paddle")
  155. if "paddle_tensorrt" in supported_pseudo_backends:
  156. supported_pseudo_backends.remove("paddle_tensorrt")
  157. if "paddle_tensorrt_fp16" in supported_pseudo_backends:
  158. supported_pseudo_backends.remove("paddle_tensorrt_fp16")
  159. candidate_backends = []
  160. backend_to_pseudo_backend = {}
  161. for pb in supported_pseudo_backends:
  162. if pb.startswith("paddle"):
  163. backend = "paddle"
  164. elif pb.startswith("tensorrt"):
  165. backend = "tensorrt"
  166. else:
  167. backend = pb
  168. if available_backends is not None and backend not in available_backends:
  169. continue
  170. candidate_backends.append(backend)
  171. backend_to_pseudo_backend[backend] = pb
  172. if not candidate_backends:
  173. return None, "No inference backend can be selected."
  174. if hpi_config.backend is not None:
  175. if hpi_config.backend not in candidate_backends:
  176. return (
  177. None,
  178. f"{repr(hpi_config.backend)} is not a supported inference backend.",
  179. )
  180. suggested_backend = hpi_config.backend
  181. else:
  182. # The first backend is the preferred one.
  183. suggested_backend = candidate_backends[0]
  184. suggested_backend_config = {}
  185. if suggested_backend == "paddle":
  186. pseudo_backend = backend_to_pseudo_backend["paddle"]
  187. assert pseudo_backend in (
  188. "paddle",
  189. "paddle_tensorrt",
  190. "paddle_tensorrt_fp16",
  191. ), pseudo_backend
  192. if pseudo_backend == "paddle_tensorrt":
  193. suggested_backend_config.update({"run_mode": "trt_fp32"})
  194. elif pseudo_backend == "paddle_tensorrt_fp16":
  195. # TODO: Check if the target device supports FP16.
  196. suggested_backend_config.update({"run_mode": "trt_fp16"})
  197. elif suggested_backend == "tensorrt":
  198. pseudo_backend = backend_to_pseudo_backend["tensorrt"]
  199. assert pseudo_backend in ("tensorrt", "tensorrt_fp16"), pseudo_backend
  200. if pseudo_backend == "tensorrt_fp16":
  201. suggested_backend_config.update({"precision": "fp16"})
  202. if hpi_config.backend_config is not None:
  203. suggested_backend_config.update(hpi_config.backend_config)
  204. return suggested_backend, suggested_backend_config