static_infer.py 11 KB

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