static_infer.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. if not self.option:
  90. self.option = PaddlePredictorOption()
  91. logging.debug(f"Env: {self.option}")
  92. (
  93. predictor,
  94. input_handlers,
  95. output_handlers,
  96. ) = self._create()
  97. self.copy2gpu = Copy2GPU(input_handlers)
  98. self.copy2cpu = Copy2CPU(output_handlers)
  99. self.infer = Infer(predictor)
  100. self.option.changed = False
  101. def _create(
  102. self,
  103. ) -> Tuple[
  104. paddle.base.libpaddle.PaddleInferPredictor,
  105. paddle.base.libpaddle.PaddleInferTensor,
  106. paddle.base.libpaddle.PaddleInferTensor,
  107. ]:
  108. """_create"""
  109. from lazy_paddle.inference import Config, create_predictor
  110. if FLAGS_json_format_model:
  111. model_file = (self.model_dir / f"{self.model_prefix}.json").as_posix()
  112. # when FLAGS_json_format_model is not set, use inference.json if exist, otherwise inference.pdmodel
  113. else:
  114. model_file = self.model_dir / f"{self.model_prefix}.json"
  115. if model_file.exists():
  116. model_file = model_file.as_posix()
  117. # default by `pdmodel` suffix
  118. else:
  119. model_file = (
  120. self.model_dir / f"{self.model_prefix}.pdmodel"
  121. ).as_posix()
  122. params_file = (self.model_dir / f"{self.model_prefix}.pdiparams").as_posix()
  123. config = Config(model_file, params_file)
  124. config.enable_memory_optim()
  125. if self.option.device in ("gpu", "dcu"):
  126. if self.option.device == "gpu":
  127. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  128. config.enable_use_gpu(100, self.option.device_id)
  129. if self.option.device == "gpu":
  130. # NOTE: The pptrt settings are not aligned with those of FD.
  131. precision_map = {
  132. "trt_int8": Config.Precision.Int8,
  133. "trt_fp32": Config.Precision.Float32,
  134. "trt_fp16": Config.Precision.Half,
  135. }
  136. if self.option.run_mode in precision_map.keys():
  137. config.enable_tensorrt_engine(
  138. workspace_size=(1 << 25) * self.option.batch_size,
  139. max_batch_size=self.option.batch_size,
  140. min_subgraph_size=self.option.min_subgraph_size,
  141. precision_mode=precision_map[self.option.run_mode],
  142. use_static=self.option.trt_use_static,
  143. use_calib_mode=self.option.trt_calib_mode,
  144. )
  145. if not os.path.exists(self.option.shape_info_filename):
  146. logging.info(
  147. f"Dynamic shape info is collected into: {self.option.shape_info_filename}"
  148. )
  149. collect_trt_shapes(
  150. model_file,
  151. params_file,
  152. self.option.device_id,
  153. self.option.shape_info_filename,
  154. self.option.trt_dynamic_shapes,
  155. )
  156. else:
  157. logging.info(
  158. f"A dynamic shape info file ( {self.option.shape_info_filename} ) already exists. No need to collect again."
  159. )
  160. config.enable_tuned_tensorrt_dynamic_shape(
  161. self.option.shape_info_filename, True
  162. )
  163. elif self.option.device == "npu":
  164. config.enable_custom_device("npu")
  165. elif self.option.device == "xpu":
  166. pass
  167. elif self.option.device == "mlu":
  168. config.enable_custom_device("mlu")
  169. else:
  170. assert self.option.device == "cpu"
  171. config.disable_gpu()
  172. if "mkldnn" in self.option.run_mode:
  173. try:
  174. config.enable_mkldnn()
  175. if "bf16" in self.option.run_mode:
  176. config.enable_mkldnn_bfloat16()
  177. except Exception as e:
  178. logging.warning(
  179. "MKL-DNN is not available. We will disable MKL-DNN."
  180. )
  181. config.set_mkldnn_cache_capacity(-1)
  182. else:
  183. if hasattr(config, "disable_mkldnn"):
  184. config.disable_mkldnn()
  185. # Disable paddle inference logging
  186. config.disable_glog_info()
  187. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  188. if self.option.device in ("cpu", "gpu"):
  189. if not (
  190. self.option.device == "gpu" and self.option.run_mode.startswith("trt")
  191. ):
  192. if hasattr(config, "enable_new_ir"):
  193. config.enable_new_ir(self.option.enable_new_ir)
  194. if hasattr(config, "enable_new_executor"):
  195. config.enable_new_executor()
  196. config.set_optimization_level(3)
  197. for del_p in self.option.delete_pass:
  198. config.delete_pass(del_p)
  199. if self.option.device in ("gpu", "dcu"):
  200. if paddle.is_compiled_with_rocm():
  201. # Delete unsupported passes in dcu
  202. config.delete_pass("conv2d_add_act_fuse_pass")
  203. config.delete_pass("conv2d_add_fuse_pass")
  204. predictor = create_predictor(config)
  205. # Get input and output handlers
  206. input_names = predictor.get_input_names()
  207. input_names.sort()
  208. input_handlers = []
  209. output_handlers = []
  210. for input_name in input_names:
  211. input_handler = predictor.get_input_handle(input_name)
  212. input_handlers.append(input_handler)
  213. output_names = predictor.get_output_names()
  214. for output_name in output_names:
  215. output_handler = predictor.get_output_handle(output_name)
  216. output_handlers.append(output_handler)
  217. return predictor, input_handlers, output_handlers
  218. def __call__(self, x) -> List[Any]:
  219. if self.option.changed:
  220. self._reset()
  221. self.copy2gpu(x)
  222. self.infer()
  223. pred = self.copy2cpu()
  224. return pred
  225. @property
  226. def benchmark(self):
  227. return {
  228. "Copy2GPU": self.copy2gpu,
  229. "Infer": self.infer,
  230. "Copy2CPU": self.copy2cpu,
  231. }