pp_option.py 10 KB

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