pp_option.py 11 KB

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