static_infer.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 self.option.shape_info_filename is None:
  152. shape_range_info_path = (
  153. self.model_dir / "shape_range_info.pbtxt"
  154. ).as_posix()
  155. else:
  156. shape_range_info_path = self.option.shape_info_filename
  157. if not os.path.exists(shape_range_info_path):
  158. logging.info(
  159. f"Dynamic shape info is collected into: {shape_range_info_path}"
  160. )
  161. collect_trt_shapes(
  162. model_file,
  163. params_file,
  164. self.option.device_id,
  165. shape_range_info_path,
  166. self.option.trt_dynamic_shapes,
  167. )
  168. else:
  169. logging.info(
  170. f"A dynamic shape info file ( {shape_range_info_path} ) already exists. No need to collect again."
  171. )
  172. self.option.shape_info_filename = shape_range_info_path
  173. else:
  174. trt_save_path = (
  175. Path(self.model_dir) / "trt" / self.model_prefix
  176. ).as_posix()
  177. pp_model_path = (Path(self.model_dir) / self.model_prefix).as_posix()
  178. convert_trt(
  179. self.option.run_mode,
  180. pp_model_path,
  181. trt_save_path,
  182. self.option.trt_dynamic_shapes,
  183. )
  184. model_file = trt_save_path + ".json"
  185. params_file = trt_save_path + ".pdiparams"
  186. config = Config(model_file, params_file)
  187. if self.option.device == "gpu":
  188. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  189. config.enable_use_gpu(100, self.option.device_id)
  190. if not self.option.run_mode.startswith("trt"):
  191. if hasattr(config, "enable_new_ir"):
  192. config.enable_new_ir(self.option.enable_new_ir)
  193. if hasattr(config, "enable_new_executor"):
  194. config.enable_new_executor()
  195. config.set_optimization_level(3)
  196. # NOTE: The pptrt settings are not aligned with those of FD.
  197. else:
  198. if not USE_PIR_TRT:
  199. precision_map = {
  200. "trt_int8": Config.Precision.Int8,
  201. "trt_fp32": Config.Precision.Float32,
  202. "trt_fp16": Config.Precision.Half,
  203. }
  204. config.enable_tensorrt_engine(
  205. workspace_size=(1 << 30) * self.option.batch_size,
  206. max_batch_size=self.option.batch_size,
  207. min_subgraph_size=self.option.min_subgraph_size,
  208. precision_mode=precision_map[self.option.run_mode],
  209. use_static=self.option.trt_use_static,
  210. use_calib_mode=self.option.trt_calib_mode,
  211. )
  212. config.enable_tuned_tensorrt_dynamic_shape(
  213. self.option.shape_info_filename, True
  214. )
  215. elif self.option.device == "npu":
  216. config.enable_custom_device("npu")
  217. elif self.option.device == "xpu":
  218. pass
  219. elif self.option.device == "mlu":
  220. config.enable_custom_device("mlu")
  221. elif self.option.device == "dcu":
  222. if paddle.is_compiled_with_rocm():
  223. # Delete unsupported passes in dcu
  224. config.delete_pass("conv2d_add_act_fuse_pass")
  225. config.delete_pass("conv2d_add_fuse_pass")
  226. else:
  227. assert self.option.device == "cpu"
  228. config.disable_gpu()
  229. if "mkldnn" in self.option.run_mode:
  230. try:
  231. config.enable_mkldnn()
  232. if "bf16" in self.option.run_mode:
  233. config.enable_mkldnn_bfloat16()
  234. except Exception as e:
  235. logging.warning(
  236. "MKL-DNN is not available. We will disable MKL-DNN."
  237. )
  238. config.set_mkldnn_cache_capacity(-1)
  239. else:
  240. if hasattr(config, "disable_mkldnn"):
  241. config.disable_mkldnn()
  242. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  243. if hasattr(config, "enable_new_ir"):
  244. config.enable_new_ir(self.option.enable_new_ir)
  245. if hasattr(config, "enable_new_executor"):
  246. config.enable_new_executor()
  247. config.set_optimization_level(3)
  248. config.enable_memory_optim()
  249. for del_p in self.option.delete_pass:
  250. config.delete_pass(del_p)
  251. # Disable paddle inference logging
  252. if not DEBUG:
  253. config.disable_glog_info()
  254. predictor = create_predictor(config)
  255. # Get input and output handlers
  256. input_names = predictor.get_input_names()
  257. input_names.sort()
  258. input_handlers = []
  259. output_handlers = []
  260. for input_name in input_names:
  261. input_handler = predictor.get_input_handle(input_name)
  262. input_handlers.append(input_handler)
  263. output_names = predictor.get_output_names()
  264. for output_name in output_names:
  265. output_handler = predictor.get_output_handle(output_name)
  266. output_handlers.append(output_handler)
  267. return predictor, input_handlers, output_handlers
  268. def __call__(self, x) -> List[Any]:
  269. if self.option.changed:
  270. self._reset()
  271. self.copy2gpu(x)
  272. self.infer()
  273. pred = self.copy2cpu()
  274. return pred
  275. @property
  276. def benchmark(self):
  277. return {
  278. "Copy2GPU": self.copy2gpu,
  279. "Infer": self.infer,
  280. "Copy2CPU": self.copy2cpu,
  281. }