pp_option.py 10 KB

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