static_infer.py 11 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. from typing import Union, Tuple, List, Dict, Any, Iterator
  15. import os
  16. import shutil
  17. from pathlib import Path
  18. import lazy_paddle as paddle
  19. import numpy as np
  20. from ....utils.flags import DEBUG, FLAGS_json_format_model, USE_PIR_TRT
  21. from ....utils import logging
  22. from ...utils.pp_option import PaddlePredictorOption
  23. def collect_trt_shapes(
  24. model_file, model_params, gpu_id, shape_range_info_path, trt_dynamic_shapes
  25. ):
  26. config = paddle.inference.Config(model_file, model_params)
  27. config.enable_use_gpu(100, gpu_id)
  28. min_arrs, opt_arrs, max_arrs = {}, {}, {}
  29. for name, candidate_shapes in trt_dynamic_shapes.items():
  30. min_shape, opt_shape, max_shape = candidate_shapes
  31. min_arrs[name] = np.ones(min_shape, dtype=np.float32)
  32. opt_arrs[name] = np.ones(opt_shape, dtype=np.float32)
  33. max_arrs[name] = np.ones(max_shape, dtype=np.float32)
  34. config.collect_shape_range_info(shape_range_info_path)
  35. predictor = paddle.inference.create_predictor(config)
  36. # opt_arrs would be used twice to simulate the most common situations
  37. for arrs in [min_arrs, opt_arrs, opt_arrs, max_arrs]:
  38. for name, arr in arrs.items():
  39. input_handler = predictor.get_input_handle(name)
  40. input_handler.reshape(arr.shape)
  41. input_handler.copy_from_cpu(arr)
  42. predictor.run()
  43. def convert_trt(mode, pp_model_path, trt_save_path, trt_dynamic_shapes):
  44. from lazy_paddle.tensorrt.export import (
  45. Input,
  46. TensorRTConfig,
  47. convert,
  48. PrecisionMode,
  49. )
  50. precision_map = {
  51. "trt_int8": PrecisionMode.INT8,
  52. "trt_fp32": PrecisionMode.FP32,
  53. "trt_fp16": PrecisionMode.FP16,
  54. }
  55. trt_inputs = []
  56. for name, candidate_shapes in trt_dynamic_shapes.items():
  57. min_shape, opt_shape, max_shape = candidate_shapes
  58. trt_input = Input(
  59. min_input_shape=min_shape,
  60. optim_input_shape=opt_shape,
  61. max_input_shape=max_shape,
  62. )
  63. trt_inputs.append(trt_input)
  64. # Create TensorRTConfig
  65. trt_config = TensorRTConfig(inputs=trt_inputs)
  66. trt_config.precision_mode = precision_map[mode]
  67. trt_config.save_model_dir = trt_save_path
  68. convert(pp_model_path, trt_config)
  69. class Copy2GPU:
  70. def __init__(self, input_handlers):
  71. super().__init__()
  72. self.input_handlers = input_handlers
  73. def __call__(self, x):
  74. for idx in range(len(x)):
  75. self.input_handlers[idx].reshape(x[idx].shape)
  76. self.input_handlers[idx].copy_from_cpu(x[idx])
  77. class Copy2CPU:
  78. def __init__(self, output_handlers):
  79. super().__init__()
  80. self.output_handlers = output_handlers
  81. def __call__(self):
  82. output = []
  83. for out_tensor in self.output_handlers:
  84. batch = out_tensor.copy_to_cpu()
  85. output.append(batch)
  86. return output
  87. class Infer:
  88. def __init__(self, predictor):
  89. super().__init__()
  90. self.predictor = predictor
  91. def __call__(self):
  92. self.predictor.run()
  93. class StaticInfer:
  94. """Predictor based on Paddle Inference"""
  95. def __init__(
  96. self, model_dir: str, model_prefix: str, option: PaddlePredictorOption
  97. ) -> None:
  98. super().__init__()
  99. self.model_dir = model_dir
  100. self.model_prefix = model_prefix
  101. self._update_option(option)
  102. def _update_option(self, option: PaddlePredictorOption) -> None:
  103. if self.option and option == self.option:
  104. return
  105. self._option = option
  106. self._reset()
  107. @property
  108. def option(self) -> PaddlePredictorOption:
  109. return self._option if hasattr(self, "_option") else None
  110. @option.setter
  111. def option(self, option: Union[None, PaddlePredictorOption]) -> None:
  112. if option:
  113. self._update_option(option)
  114. def _reset(self) -> None:
  115. logging.debug(f"Env: {self.option}")
  116. (
  117. predictor,
  118. input_handlers,
  119. output_handlers,
  120. ) = self._create()
  121. self.copy2gpu = Copy2GPU(input_handlers)
  122. self.copy2cpu = Copy2CPU(output_handlers)
  123. self.infer = Infer(predictor)
  124. self.option.changed = False
  125. def _create(
  126. self,
  127. ) -> Tuple[
  128. "paddle.base.libpaddle.PaddleInferPredictor",
  129. "paddle.base.libpaddle.PaddleInferTensor",
  130. "paddle.base.libpaddle.PaddleInferTensor",
  131. ]:
  132. """_create"""
  133. from lazy_paddle.inference import Config, create_predictor
  134. if FLAGS_json_format_model:
  135. model_file = (self.model_dir / f"{self.model_prefix}.json").as_posix()
  136. # when FLAGS_json_format_model is not set, use inference.json if exist, otherwise inference.pdmodel
  137. else:
  138. model_file = self.model_dir / f"{self.model_prefix}.json"
  139. if model_file.exists():
  140. model_file = model_file.as_posix()
  141. # default by `pdmodel` suffix
  142. else:
  143. model_file = (
  144. self.model_dir / f"{self.model_prefix}.pdmodel"
  145. ).as_posix()
  146. params_file = (self.model_dir / f"{self.model_prefix}.pdiparams").as_posix()
  147. # for TRT
  148. if self.option.run_mode.startswith("trt"):
  149. assert self.option.device == "gpu"
  150. if not USE_PIR_TRT:
  151. if not os.path.exists(self.option.shape_info_filename):
  152. logging.info(
  153. f"Dynamic shape info is collected into: {self.option.shape_info_filename}"
  154. )
  155. collect_trt_shapes(
  156. model_file,
  157. params_file,
  158. self.option.device_id,
  159. self.option.shape_info_filename,
  160. self.option.trt_dynamic_shapes,
  161. )
  162. else:
  163. logging.info(
  164. f"A dynamic shape info file ( {self.option.shape_info_filename} ) already exists. No need to collect again."
  165. )
  166. else:
  167. trt_save_path = (
  168. Path(self.model_dir) / "trt" / self.model_prefix
  169. ).as_posix()
  170. pp_model_path = (Path(self.model_dir) / self.model_prefix).as_posix()
  171. convert_trt(
  172. self.option.run_mode,
  173. pp_model_path,
  174. trt_save_path,
  175. self.option.trt_dynamic_shapes,
  176. )
  177. model_file = trt_save_path + ".json"
  178. params_file = trt_save_path + ".pdiparams"
  179. config = Config(model_file, params_file)
  180. if self.option.device == "gpu":
  181. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  182. config.enable_use_gpu(100, self.option.device_id)
  183. if not self.option.run_mode.startswith("trt"):
  184. if hasattr(config, "enable_new_ir"):
  185. config.enable_new_ir(self.option.enable_new_ir)
  186. if hasattr(config, "enable_new_executor"):
  187. config.enable_new_executor()
  188. config.set_optimization_level(3)
  189. # NOTE: The pptrt settings are not aligned with those of FD.
  190. else:
  191. if not USE_PIR_TRT:
  192. precision_map = {
  193. "trt_int8": Config.Precision.Int8,
  194. "trt_fp32": Config.Precision.Float32,
  195. "trt_fp16": Config.Precision.Half,
  196. }
  197. config.enable_tensorrt_engine(
  198. workspace_size=(1 << 25) * self.option.batch_size,
  199. max_batch_size=self.option.batch_size,
  200. min_subgraph_size=self.option.min_subgraph_size,
  201. precision_mode=precision_map[self.option.run_mode],
  202. use_static=self.option.trt_use_static,
  203. use_calib_mode=self.option.trt_calib_mode,
  204. )
  205. config.enable_tuned_tensorrt_dynamic_shape(
  206. self.option.shape_info_filename, True
  207. )
  208. elif self.option.device == "npu":
  209. config.enable_custom_device("npu")
  210. elif self.option.device == "xpu":
  211. pass
  212. elif self.option.device == "mlu":
  213. config.enable_custom_device("mlu")
  214. elif self.option.device == "dcu":
  215. if paddle.is_compiled_with_rocm():
  216. # Delete unsupported passes in dcu
  217. config.delete_pass("conv2d_add_act_fuse_pass")
  218. config.delete_pass("conv2d_add_fuse_pass")
  219. else:
  220. assert self.option.device == "cpu"
  221. config.disable_gpu()
  222. if "mkldnn" in self.option.run_mode:
  223. try:
  224. config.enable_mkldnn()
  225. if "bf16" in self.option.run_mode:
  226. config.enable_mkldnn_bfloat16()
  227. except Exception as e:
  228. logging.warning(
  229. "MKL-DNN is not available. We will disable MKL-DNN."
  230. )
  231. config.set_mkldnn_cache_capacity(-1)
  232. else:
  233. if hasattr(config, "disable_mkldnn"):
  234. config.disable_mkldnn()
  235. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  236. if hasattr(config, "enable_new_ir"):
  237. config.enable_new_ir(self.option.enable_new_ir)
  238. if hasattr(config, "enable_new_executor"):
  239. config.enable_new_executor()
  240. config.set_optimization_level(3)
  241. config.enable_memory_optim()
  242. for del_p in self.option.delete_pass:
  243. config.delete_pass(del_p)
  244. # Disable paddle inference logging
  245. if not DEBUG:
  246. config.disable_glog_info()
  247. predictor = create_predictor(config)
  248. # Get input and output handlers
  249. input_names = predictor.get_input_names()
  250. input_names.sort()
  251. input_handlers = []
  252. output_handlers = []
  253. for input_name in input_names:
  254. input_handler = predictor.get_input_handle(input_name)
  255. input_handlers.append(input_handler)
  256. output_names = predictor.get_output_names()
  257. for output_name in output_names:
  258. output_handler = predictor.get_output_handle(output_name)
  259. output_handlers.append(output_handler)
  260. return predictor, input_handlers, output_handlers
  261. def __call__(self, x) -> List[Any]:
  262. if self.option.changed:
  263. self._reset()
  264. self.copy2gpu(x)
  265. self.infer()
  266. pred = self.copy2cpu()
  267. return pred
  268. @property
  269. def benchmark(self):
  270. return {
  271. "Copy2GPU": self.copy2gpu,
  272. "Infer": self.infer,
  273. "Copy2CPU": self.copy2cpu,
  274. }