pp_option.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 os
  15. from typing import Dict, List
  16. from ...utils import logging
  17. from ...utils.device import (
  18. check_supported_device_type,
  19. get_default_device,
  20. parse_device,
  21. set_env_for_device_type,
  22. )
  23. from .new_ir_blacklist import NEWIR_BLOCKLIST
  24. from .trt_blacklist import TRT_BLOCKLIST
  25. from .trt_config import TRT_PRECISION_MAP, TRT_CFG
  26. class PaddlePredictorOption(object):
  27. """Paddle Inference Engine Option"""
  28. # NOTE: TRT modes start with `trt_`
  29. SUPPORT_RUN_MODE = (
  30. "paddle",
  31. "paddle_fp32",
  32. "paddle_fp16",
  33. "trt_fp32",
  34. "trt_fp16",
  35. "trt_int8",
  36. "mkldnn",
  37. "mkldnn_bf16",
  38. )
  39. SUPPORT_DEVICE = ("gpu", "cpu", "npu", "xpu", "mlu", "dcu", "gcu")
  40. def __init__(self, model_name=None, **kwargs):
  41. super().__init__()
  42. self.model_name = model_name
  43. self._cfg = {}
  44. self._init_option(**kwargs)
  45. self._changed = False
  46. @property
  47. def changed(self):
  48. return self._changed
  49. @changed.setter
  50. def changed(self, v):
  51. assert isinstance(v, bool)
  52. self._changed = v
  53. def _init_option(self, **kwargs):
  54. for k, v in kwargs.items():
  55. if self._has_setter(k):
  56. setattr(self, k, v)
  57. else:
  58. raise Exception(
  59. f"{k} is not supported to set! The supported option is: {self._get_settable_attributes()}"
  60. )
  61. for k, v in self._get_default_config().items():
  62. self._cfg.setdefault(k, v)
  63. # for trt
  64. if self.run_mode in TRT_PRECISION_MAP:
  65. trt_cfg = TRT_CFG[self.model_name]
  66. trt_cfg["enable_tensorrt_engine"]["precision_mode"] = TRT_PRECISION_MAP[
  67. self.run_mode
  68. ]
  69. self.trt_cfg = trt_cfg
  70. def _get_default_config(self):
  71. """get default config"""
  72. device_type, device_ids = parse_device(get_default_device())
  73. default_config = {
  74. "run_mode": "paddle",
  75. "device_type": device_type,
  76. "device_id": None if device_ids is None else device_ids[0],
  77. "cpu_threads": 8,
  78. "delete_pass": [],
  79. "enable_new_ir": True if self.model_name not in NEWIR_BLOCKLIST else False,
  80. "trt_cfg": {},
  81. "trt_use_dynamic_shapes": True, # only for trt
  82. "trt_collect_shape_range_info": True, # only for trt
  83. "trt_discard_cached_shape_range_info": False, # only for trt
  84. "trt_dynamic_shapes": None, # only for trt
  85. "trt_dynamic_shape_input_data": None, # only for trt
  86. "trt_shape_range_info_path": None, # only for trt
  87. "trt_allow_rebuild_at_runtime": True, # only for trt
  88. }
  89. return default_config
  90. def _update(self, k, v):
  91. self._cfg[k] = v
  92. self.changed = True
  93. @property
  94. def run_mode(self):
  95. return self._cfg["run_mode"]
  96. @run_mode.setter
  97. def run_mode(self, run_mode: str):
  98. """set run mode"""
  99. if run_mode not in self.SUPPORT_RUN_MODE:
  100. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  101. raise ValueError(
  102. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  103. )
  104. # TRT Blocklist
  105. if run_mode.startswith("trt") and self.model_name in TRT_BLOCKLIST:
  106. logging.warning(
  107. f"The model({self.model_name}) is not supported to run in trt mode! Using `paddle` instead!"
  108. )
  109. run_mode = "paddle"
  110. self._update("run_mode", run_mode)
  111. @property
  112. def device_type(self):
  113. return self._cfg["device_type"]
  114. @device_type.setter
  115. def device_type(self, device_type):
  116. if device_type not in self.SUPPORT_DEVICE:
  117. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  118. raise ValueError(
  119. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  120. )
  121. check_supported_device_type(device_type, self.model_name)
  122. self._update("device_type", device_type)
  123. set_env_for_device_type(device_type)
  124. # XXX(gaotingquan): set flag to accelerate inference in paddle 3.0b2
  125. if device_type in ("gpu", "cpu"):
  126. os.environ["FLAGS_enable_pir_api"] = "1"
  127. @property
  128. def device_id(self):
  129. return self._cfg["device_id"]
  130. @device_id.setter
  131. def device_id(self, device_id):
  132. self._update("device_id", device_id)
  133. @property
  134. def cpu_threads(self):
  135. return self._cfg["cpu_threads"]
  136. @cpu_threads.setter
  137. def cpu_threads(self, cpu_threads):
  138. """set cpu threads"""
  139. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  140. raise Exception()
  141. self._update("cpu_threads", cpu_threads)
  142. @property
  143. def delete_pass(self):
  144. return self._cfg["delete_pass"]
  145. @delete_pass.setter
  146. def delete_pass(self, delete_pass):
  147. self._update("delete_pass", delete_pass)
  148. @property
  149. def enable_new_ir(self):
  150. return self._cfg["enable_new_ir"]
  151. @enable_new_ir.setter
  152. def enable_new_ir(self, enable_new_ir: bool):
  153. """set run mode"""
  154. self._update("enable_new_ir", enable_new_ir)
  155. @property
  156. def trt_cfg(self):
  157. return self._cfg["trt_cfg"]
  158. @trt_cfg.setter
  159. def trt_cfg(self, config: Dict):
  160. """set trt config"""
  161. assert isinstance(
  162. config, dict
  163. ), f"The trt_cfg must be `dict` type, but recived `{type(config)}` type!"
  164. self._update("trt_cfg", config)
  165. @property
  166. def trt_use_dynamic_shapes(self):
  167. return self._cfg["trt_use_dynamic_shapes"]
  168. @trt_use_dynamic_shapes.setter
  169. def trt_use_dynamic_shapes(self, trt_use_dynamic_shapes):
  170. self._update("trt_use_dynamic_shapes", trt_use_dynamic_shapes)
  171. @property
  172. def trt_collect_shape_range_info(self):
  173. return self._cfg["trt_collect_shape_range_info"]
  174. @trt_collect_shape_range_info.setter
  175. def trt_collect_shape_range_info(self, trt_collect_shape_range_info):
  176. self._update("trt_collect_shape_range_info", trt_collect_shape_range_info)
  177. @property
  178. def trt_discard_cached_shape_range_info(self):
  179. return self._cfg["trt_discard_cached_shape_range_info"]
  180. @trt_discard_cached_shape_range_info.setter
  181. def trt_discard_cached_shape_range_info(self, trt_discard_cached_shape_range_info):
  182. self._update(
  183. "trt_discard_cached_shape_range_info", trt_discard_cached_shape_range_info
  184. )
  185. @property
  186. def trt_dynamic_shapes(self):
  187. return self._cfg["trt_dynamic_shapes"]
  188. @trt_dynamic_shapes.setter
  189. def trt_dynamic_shapes(self, trt_dynamic_shapes: Dict[str, List[List[int]]]):
  190. assert isinstance(trt_dynamic_shapes, dict)
  191. for input_k in trt_dynamic_shapes:
  192. assert isinstance(trt_dynamic_shapes[input_k], list)
  193. self._update("trt_dynamic_shapes", trt_dynamic_shapes)
  194. @property
  195. def trt_dynamic_shape_input_data(self):
  196. return self._cfg["trt_dynamic_shape_input_data"]
  197. @trt_dynamic_shape_input_data.setter
  198. def trt_dynamic_shape_input_data(
  199. self, trt_dynamic_shape_input_data: Dict[str, List[float]]
  200. ):
  201. self._update("trt_dynamic_shape_input_data", trt_dynamic_shape_input_data)
  202. @property
  203. def trt_shape_range_info_path(self):
  204. return self._cfg["trt_shape_range_info_path"]
  205. @trt_shape_range_info_path.setter
  206. def trt_shape_range_info_path(self, trt_shape_range_info_path: str):
  207. """set shape info filename"""
  208. self._update("trt_shape_range_info_path", trt_shape_range_info_path)
  209. @property
  210. def trt_allow_rebuild_at_runtime(self):
  211. return self._cfg["trt_allow_rebuild_at_runtime"]
  212. @trt_allow_rebuild_at_runtime.setter
  213. def trt_allow_rebuild_at_runtime(self, trt_allow_rebuild_at_runtime):
  214. self._update("trt_allow_rebuild_at_runtime", trt_allow_rebuild_at_runtime)
  215. # For backward compatibility
  216. # TODO: Issue deprecation warnings
  217. @property
  218. def shape_info_filename(self):
  219. return self.trt_shape_range_info_path
  220. @shape_info_filename.setter
  221. def shape_info_filename(self, shape_info_filename):
  222. self.trt_shape_range_info_path = shape_info_filename
  223. def set_device(self, device: str):
  224. """set device"""
  225. if not device:
  226. return
  227. device_type, device_ids = parse_device(device)
  228. self.device_type = device_type
  229. device_id = device_ids[0] if device_ids is not None else None
  230. self.device_id = device_id
  231. if device_ids is None or len(device_ids) > 1:
  232. logging.debug(f"The device ID has been set to {device_id}.")
  233. def get_support_run_mode(self):
  234. """get supported run mode"""
  235. return self.SUPPORT_RUN_MODE
  236. def get_support_device(self):
  237. """get supported device"""
  238. return self.SUPPORT_DEVICE
  239. def __str__(self):
  240. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  241. def __getattr__(self, key):
  242. if key not in self._cfg:
  243. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  244. return self._cfg.get(key)
  245. def __eq__(self, obj):
  246. if isinstance(obj, PaddlePredictorOption):
  247. return obj._cfg == self._cfg
  248. return False
  249. def _has_setter(self, attr):
  250. prop = getattr(self.__class__, attr, None)
  251. return isinstance(prop, property) and prop.fset is not None
  252. def _get_settable_attributes(self):
  253. return [
  254. name
  255. for name, prop in vars(self.__class__).items()
  256. if isinstance(prop, property) and prop.fset is not None
  257. ]