static_infer.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 inspect
  17. from abc import abstractmethod
  18. import lazy_paddle as paddle
  19. import numpy as np
  20. from ....utils.flags import FLAGS_json_format_model
  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. class Copy2GPU:
  44. def __init__(self, input_handlers):
  45. super().__init__()
  46. self.input_handlers = input_handlers
  47. def __call__(self, x):
  48. for idx in range(len(x)):
  49. self.input_handlers[idx].reshape(x[idx].shape)
  50. self.input_handlers[idx].copy_from_cpu(x[idx])
  51. class Copy2CPU:
  52. def __init__(self, output_handlers):
  53. super().__init__()
  54. self.output_handlers = output_handlers
  55. def __call__(self):
  56. output = []
  57. for out_tensor in self.output_handlers:
  58. batch = out_tensor.copy_to_cpu()
  59. output.append(batch)
  60. return output
  61. class Infer:
  62. def __init__(self, predictor):
  63. super().__init__()
  64. self.predictor = predictor
  65. def __call__(self):
  66. self.predictor.run()
  67. class StaticInfer:
  68. """Predictor based on Paddle Inference"""
  69. def __init__(
  70. self, model_dir: str, model_prefix: str, option: PaddlePredictorOption
  71. ) -> None:
  72. super().__init__()
  73. self.model_dir = model_dir
  74. self.model_prefix = model_prefix
  75. self._update_option(option)
  76. def _update_option(self, option: PaddlePredictorOption) -> None:
  77. if self.option and option == self.option:
  78. return
  79. self._option = option
  80. self._reset()
  81. @property
  82. def option(self) -> PaddlePredictorOption:
  83. return self._option if hasattr(self, "_option") else None
  84. @option.setter
  85. def option(self, option: Union[None, PaddlePredictorOption]) -> None:
  86. if option:
  87. self._update_option(option)
  88. def _reset(self) -> None:
  89. logging.debug(f"Env: {self.option}")
  90. (
  91. predictor,
  92. input_handlers,
  93. output_handlers,
  94. ) = self._create()
  95. self.copy2gpu = Copy2GPU(input_handlers)
  96. self.copy2cpu = Copy2CPU(output_handlers)
  97. self.infer = Infer(predictor)
  98. self.option.changed = False
  99. def _create(
  100. self,
  101. ) -> Tuple[
  102. "paddle.base.libpaddle.PaddleInferPredictor",
  103. "paddle.base.libpaddle.PaddleInferTensor",
  104. "paddle.base.libpaddle.PaddleInferTensor",
  105. ]:
  106. """_create"""
  107. from lazy_paddle.inference import Config, create_predictor
  108. if FLAGS_json_format_model:
  109. model_file = (self.model_dir / f"{self.model_prefix}.json").as_posix()
  110. # when FLAGS_json_format_model is not set, use inference.json if exist, otherwise inference.pdmodel
  111. else:
  112. model_file = self.model_dir / f"{self.model_prefix}.json"
  113. if model_file.exists():
  114. model_file = model_file.as_posix()
  115. # default by `pdmodel` suffix
  116. else:
  117. model_file = (
  118. self.model_dir / f"{self.model_prefix}.pdmodel"
  119. ).as_posix()
  120. params_file = (self.model_dir / f"{self.model_prefix}.pdiparams").as_posix()
  121. config = Config(model_file, params_file)
  122. config.enable_memory_optim()
  123. if self.option.device in ("gpu", "dcu"):
  124. if self.option.device == "gpu":
  125. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  126. config.enable_use_gpu(100, self.option.device_id)
  127. if self.option.device == "gpu":
  128. # NOTE: The pptrt settings are not aligned with those of FD.
  129. precision_map = {
  130. "trt_int8": Config.Precision.Int8,
  131. "trt_fp32": Config.Precision.Float32,
  132. "trt_fp16": Config.Precision.Half,
  133. }
  134. if self.option.run_mode in precision_map.keys():
  135. config.enable_tensorrt_engine(
  136. workspace_size=(1 << 25) * self.option.batch_size,
  137. max_batch_size=self.option.batch_size,
  138. min_subgraph_size=self.option.min_subgraph_size,
  139. precision_mode=precision_map[self.option.run_mode],
  140. use_static=self.option.trt_use_static,
  141. use_calib_mode=self.option.trt_calib_mode,
  142. )
  143. if not os.path.exists(self.option.shape_info_filename):
  144. logging.info(
  145. f"Dynamic shape info is collected into: {self.option.shape_info_filename}"
  146. )
  147. collect_trt_shapes(
  148. model_file,
  149. params_file,
  150. self.option.device_id,
  151. self.option.shape_info_filename,
  152. self.option.trt_dynamic_shapes,
  153. )
  154. else:
  155. logging.info(
  156. f"A dynamic shape info file ( {self.option.shape_info_filename} ) already exists. No need to collect again."
  157. )
  158. config.enable_tuned_tensorrt_dynamic_shape(
  159. self.option.shape_info_filename, True
  160. )
  161. elif self.option.device == "npu":
  162. config.enable_custom_device("npu")
  163. elif self.option.device == "xpu":
  164. pass
  165. elif self.option.device == "mlu":
  166. config.enable_custom_device("mlu")
  167. else:
  168. assert self.option.device == "cpu"
  169. config.disable_gpu()
  170. if "mkldnn" in self.option.run_mode:
  171. try:
  172. config.enable_mkldnn()
  173. if "bf16" in self.option.run_mode:
  174. config.enable_mkldnn_bfloat16()
  175. except Exception as e:
  176. logging.warning(
  177. "MKL-DNN is not available. We will disable MKL-DNN."
  178. )
  179. config.set_mkldnn_cache_capacity(-1)
  180. else:
  181. if hasattr(config, "disable_mkldnn"):
  182. config.disable_mkldnn()
  183. # Disable paddle inference logging
  184. config.disable_glog_info()
  185. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  186. if self.option.device in ("cpu", "gpu"):
  187. if not (
  188. self.option.device == "gpu" and self.option.run_mode.startswith("trt")
  189. ):
  190. if hasattr(config, "enable_new_ir"):
  191. config.enable_new_ir(self.option.enable_new_ir)
  192. if hasattr(config, "enable_new_executor"):
  193. config.enable_new_executor()
  194. config.set_optimization_level(3)
  195. for del_p in self.option.delete_pass:
  196. config.delete_pass(del_p)
  197. if self.option.device in ("gpu", "dcu"):
  198. if paddle.is_compiled_with_rocm():
  199. # Delete unsupported passes in dcu
  200. config.delete_pass("conv2d_add_act_fuse_pass")
  201. config.delete_pass("conv2d_add_fuse_pass")
  202. predictor = create_predictor(config)
  203. # Get input and output handlers
  204. input_names = predictor.get_input_names()
  205. input_names.sort()
  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, input_handlers, output_handlers
  216. def __call__(self, x) -> List[Any]:
  217. if self.option.changed:
  218. self._reset()
  219. self.copy2gpu(x)
  220. self.infer()
  221. pred = self.copy2cpu()
  222. return pred
  223. @property
  224. def benchmark(self):
  225. return {
  226. "Copy2GPU": self.copy2gpu,
  227. "Infer": self.infer,
  228. "Copy2CPU": self.copy2cpu,
  229. }