paddle_inference_predictor.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 functools import wraps, partial
  16. from paddle.inference import Config, create_predictor
  17. from .....utils import logging
  18. def register(register_map, key):
  19. """register the option setting func
  20. """
  21. def decorator(func):
  22. register_map[key] = func
  23. @wraps(func)
  24. def wrapper(self, *args, **kwargs):
  25. return func(self, *args, **kwargs)
  26. return wrapper
  27. return decorator
  28. class PaddleInferenceOption(object):
  29. """Paddle Inference Engine Option
  30. """
  31. SUPPORT_RUN_MODE = ('paddle', 'trt_fp32', 'trt_fp16', 'trt_int8', 'mkldnn',
  32. 'mkldnn_bf16')
  33. SUPPORT_DEVICE = ('gpu', 'cpu', 'npu', 'xpu', 'mlu')
  34. _REGISTER_MAP = {}
  35. register2self = partial(register, _REGISTER_MAP)
  36. def __init__(self, **kwargs):
  37. super().__init__()
  38. self._cfg = {}
  39. self._init_option(**kwargs)
  40. def _init_option(self, **kwargs):
  41. for k, v in kwargs.items():
  42. if k not in self._REGISTER_MAP:
  43. raise Exception(
  44. f"{k} is not supported to set! The supported option is: \
  45. {list(self._REGISTER_MAP.keys())}")
  46. self._REGISTER_MAP.get(k)(self, v)
  47. for k, v in self._get_default_config().items():
  48. self._cfg.setdefault(k, v)
  49. def _get_default_config(cls):
  50. """ get default config """
  51. return {
  52. 'run_mode': 'paddle',
  53. 'batch_size': 1,
  54. 'device': 'gpu',
  55. 'min_subgraph_size': 3,
  56. 'shape_info_filename': None,
  57. 'trt_calib_mode': False,
  58. 'cpu_threads': 1,
  59. 'trt_use_static': False
  60. }
  61. @register2self('run_mode')
  62. def set_run_mode(self, run_mode: str):
  63. """set run mode
  64. """
  65. if run_mode not in self.SUPPORT_RUN_MODE:
  66. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  67. raise ValueError(
  68. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  69. )
  70. self._cfg['run_mode'] = run_mode
  71. @register2self('batch_size')
  72. def set_batch_size(self, batch_size: int):
  73. """set batch size
  74. """
  75. if not isinstance(batch_size, int) or batch_size < 1:
  76. raise Exception()
  77. self._cfg['batch_size'] = batch_size
  78. @register2self('device')
  79. def set_device(self, device: str):
  80. """set device
  81. """
  82. device = device.split(":")[0]
  83. if device.lower() not in self.SUPPORT_DEVICE:
  84. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  85. raise ValueError(
  86. f"`device` must be {support_run_mode_str}, but received {repr(device)}."
  87. )
  88. self._cfg['device'] = device.lower()
  89. @register2self('min_subgraph_size')
  90. def set_min_subgraph_size(self, min_subgraph_size: int):
  91. """set min subgraph size
  92. """
  93. if not isinstance(min_subgraph_size, int):
  94. raise Exception()
  95. self._cfg['min_subgraph_size'] = min_subgraph_size
  96. @register2self('shape_info_filename')
  97. def set_shape_info_filename(self, shape_info_filename: str):
  98. """set shape info filename
  99. """
  100. self._cfg['shape_info_filename'] = shape_info_filename
  101. @register2self('trt_calib_mode')
  102. def set_trt_calib_mode(self, trt_calib_mode):
  103. """set trt calib mode
  104. """
  105. self._cfg['trt_calib_mode'] = trt_calib_mode
  106. @register2self('cpu_threads')
  107. def set_cpu_threads(self, cpu_threads):
  108. """set cpu threads
  109. """
  110. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  111. raise Exception()
  112. self._cfg['cpu_threads'] = cpu_threads
  113. @register2self('trt_use_static')
  114. def set_trt_use_static(self, trt_use_static):
  115. """set trt use static
  116. """
  117. self._cfg['trt_use_static'] = trt_use_static
  118. def get_support_run_mode(self):
  119. """get supported run mode
  120. """
  121. return self.SUPPORT_RUN_MODE
  122. def get_support_device(self):
  123. """get supported device
  124. """
  125. return self.SUPPORT_DEVICE
  126. def __str__(self):
  127. return "\n " + "\n ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  128. def __getattr__(self, key):
  129. if key not in self._cfg:
  130. raise Exception()
  131. return self._cfg.get(key)
  132. class _PaddleInferencePredictor(object):
  133. """ Predictor based on Paddle Inference """
  134. def __init__(self, param_path, model_path, option, delete_pass=[]):
  135. super().__init__()
  136. self.predictor, self.inference_config, self.input_names, self.input_handlers, self.output_handlers = \
  137. self._create(param_path, model_path, option, delete_pass=delete_pass)
  138. def _create(self, param_path, model_path, option, delete_pass):
  139. """ _create """
  140. if not os.path.exists(model_path) or not os.path.exists(param_path):
  141. raise FileNotFoundError(
  142. f"Please ensure {model_path} and {param_path} exist.")
  143. model_buffer, param_buffer = self._read_model_param(model_path,
  144. param_path)
  145. config = Config()
  146. config.set_model_buffer(model_buffer,
  147. len(model_buffer), param_buffer,
  148. len(param_buffer))
  149. if option.device == 'gpu':
  150. config.enable_use_gpu(200, 0)
  151. elif option.device == 'npu':
  152. config.enable_custom_device('npu')
  153. elif option.device == 'xpu':
  154. config.enable_custom_device('npu')
  155. elif option.device == 'mlu':
  156. config.enable_custom_device('mlu')
  157. else:
  158. assert option.device == 'cpu'
  159. config.disable_gpu()
  160. if 'mkldnn' in option.run_mode:
  161. try:
  162. config.enable_mkldnn()
  163. config.set_cpu_math_library_num_threads(option.cpu_threads)
  164. if 'bf16' in option.run_mode:
  165. config.enable_mkldnn_bfloat16()
  166. except Exception as e:
  167. logging.warning(
  168. "MKL-DNN is not available. We will disable MKL-DNN.")
  169. precision_map = {
  170. 'trt_int8': Config.Precision.Int8,
  171. 'trt_fp32': Config.Precision.Float32,
  172. 'trt_fp16': Config.Precision.Half
  173. }
  174. if option.run_mode in precision_map.keys():
  175. config.enable_tensorrt_engine(
  176. workspace_size=(1 << 25) * option.batch_size,
  177. max_batch_size=option.batch_size,
  178. min_subgraph_size=option.min_subgraph_size,
  179. precision_mode=precision_map[option.run_mode],
  180. trt_use_static=option.trt_use_static,
  181. use_calib_mode=option.trt_calib_mode)
  182. if option.shape_info_filename is not None:
  183. if not os.path.exists(option.shape_info_filename):
  184. config.collect_shape_range_info(option.shape_info_filename)
  185. logging.info(
  186. f"Dynamic shape info is collected into: {option.shape_info_filename}"
  187. )
  188. else:
  189. logging.info(
  190. f"A dynamic shape info file ( {option.shape_info_filename} ) already exists. \
  191. No need to generate again.")
  192. config.enable_tuned_tensorrt_dynamic_shape(
  193. option.shape_info_filename, True)
  194. # Disable paddle inference logging
  195. config.disable_glog_info()
  196. for del_p in delete_pass:
  197. config.delete_pass(del_p)
  198. # Enable shared memory
  199. config.enable_memory_optim()
  200. config.switch_ir_optim(True)
  201. # Disable feed, fetch OP, needed by zero_copy_run
  202. config.switch_use_feed_fetch_ops(False)
  203. predictor = create_predictor(config)
  204. # Get input and output handlers
  205. input_names = predictor.get_input_names()
  206. input_handlers = []
  207. output_handlers = []
  208. for input_name in input_names:
  209. input_handler = predictor.get_input_handle(input_name)
  210. input_handlers.append(input_handler)
  211. output_names = predictor.get_output_names()
  212. for output_name in output_names:
  213. output_handler = predictor.get_output_handle(output_name)
  214. output_handlers.append(output_handler)
  215. return predictor, config, input_names, input_handlers, output_handlers
  216. def _read_model_param(self, model_path, param_path):
  217. """ read model and param """
  218. model_file = open(model_path, 'rb')
  219. param_file = open(param_path, 'rb')
  220. model_buffer = model_file.read()
  221. param_buffer = param_file.read()
  222. return model_buffer, param_buffer
  223. def get_input_names(self):
  224. """ get input names """
  225. return self.input_names
  226. def predict(self, x):
  227. """ predict """
  228. for idx in range(len(x)):
  229. self.input_handlers[idx].reshape(x[idx].shape)
  230. self.input_handlers[idx].copy_from_cpu(x[idx])
  231. self.predictor.run()
  232. res = []
  233. for out_tensor in self.output_handlers:
  234. out_arr = out_tensor.copy_to_cpu()
  235. res.append(out_arr)
  236. return res