predictor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. import os
  15. from abc import abstractmethod
  16. import lazy_paddle as paddle
  17. import numpy as np
  18. from ....utils.flags import FLAGS_json_format_model
  19. from ....utils import logging
  20. from ...utils.pp_option import PaddlePredictorOption
  21. from ..base import BaseComponent
  22. def collect_trt_shapes(
  23. model_file, model_params, gpu_id, shape_range_info_path, trt_dynamic_shapes
  24. ):
  25. config = paddle.inference.Config(model_file, model_params)
  26. config.enable_use_gpu(100, gpu_id)
  27. min_arrs, opt_arrs, max_arrs = {}, {}, {}
  28. for name, candidate_shapes in trt_dynamic_shapes.items():
  29. min_shape, opt_shape, max_shape = candidate_shapes
  30. min_arrs[name] = np.ones(min_shape, dtype=np.float32)
  31. opt_arrs[name] = np.ones(opt_shape, dtype=np.float32)
  32. max_arrs[name] = np.ones(max_shape, dtype=np.float32)
  33. config.collect_shape_range_info(shape_range_info_path)
  34. predictor = paddle.inference.create_predictor(config)
  35. # opt_arrs would be used twice to simulate the most common situations
  36. for arrs in [min_arrs, opt_arrs, opt_arrs, max_arrs]:
  37. for name, arr in arrs.items():
  38. input_handler = predictor.get_input_handle(name)
  39. input_handler.reshape(arr.shape)
  40. input_handler.copy_from_cpu(arr)
  41. predictor.run()
  42. class Copy2GPU(BaseComponent):
  43. def __init__(self, input_handlers):
  44. super().__init__()
  45. self.input_handlers = input_handlers
  46. def apply(self, x):
  47. for idx in range(len(x)):
  48. self.input_handlers[idx].reshape(x[idx].shape)
  49. self.input_handlers[idx].copy_from_cpu(x[idx])
  50. class Copy2CPU(BaseComponent):
  51. def __init__(self, output_handlers):
  52. super().__init__()
  53. self.output_handlers = output_handlers
  54. def apply(self):
  55. output = []
  56. for out_tensor in self.output_handlers:
  57. batch = out_tensor.copy_to_cpu()
  58. output.append(batch)
  59. return output
  60. class Infer(BaseComponent):
  61. def __init__(self, predictor):
  62. super().__init__()
  63. self.predictor = predictor
  64. def apply(self):
  65. self.predictor.run()
  66. class BasePaddlePredictor(BaseComponent):
  67. """Predictor based on Paddle Inference"""
  68. OUTPUT_KEYS = "pred"
  69. DEAULT_OUTPUTS = {"pred": "pred"}
  70. ENABLE_BATCH = True
  71. def __init__(self, model_dir, model_prefix, option):
  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):
  77. if option:
  78. if self.option and option == self.option:
  79. return
  80. self._option = option
  81. self._reset()
  82. @property
  83. def option(self):
  84. return self._option if hasattr(self, "_option") else None
  85. @option.setter
  86. def option(self, option):
  87. self._update_option(option)
  88. def _reset(self):
  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(self):
  102. """_create"""
  103. from lazy_paddle.inference import Config, create_predictor
  104. model_postfix = ".json" if FLAGS_json_format_model else ".pdmodel"
  105. model_file = (self.model_dir / f"{self.model_prefix}{model_postfix}").as_posix()
  106. params_file = (self.model_dir / f"{self.model_prefix}.pdiparams").as_posix()
  107. config = Config(model_file, params_file)
  108. config.enable_memory_optim()
  109. if self.option.device in ("gpu", "dcu"):
  110. if self.option.device == "gpu":
  111. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  112. config.enable_use_gpu(100, self.option.device_id)
  113. if self.option.device == "gpu":
  114. # NOTE: The pptrt settings are not aligned with those of FD.
  115. precision_map = {
  116. "trt_int8": Config.Precision.Int8,
  117. "trt_fp32": Config.Precision.Float32,
  118. "trt_fp16": Config.Precision.Half,
  119. }
  120. if self.option.run_mode in precision_map.keys():
  121. config.enable_tensorrt_engine(
  122. workspace_size=(1 << 30) * self.option.batch_size,
  123. max_batch_size=self.option.batch_size,
  124. min_subgraph_size=self.option.min_subgraph_size,
  125. precision_mode=precision_map[self.option.run_mode],
  126. use_static=self.option.trt_use_static,
  127. use_calib_mode=self.option.trt_calib_mode,
  128. )
  129. if not os.path.exists(self.option.shape_info_filename):
  130. logging.info(
  131. f"Dynamic shape info is collected into: {self.option.shape_info_filename}"
  132. )
  133. collect_trt_shapes(
  134. model_file,
  135. params_file,
  136. self.option.device_id,
  137. self.option.shape_info_filename,
  138. self.option.trt_dynamic_shapes,
  139. )
  140. else:
  141. logging.info(
  142. f"A dynamic shape info file ( {self.option.shape_info_filename} ) already exists. No need to collect again."
  143. )
  144. config.enable_tuned_tensorrt_dynamic_shape(
  145. self.option.shape_info_filename, True
  146. )
  147. elif self.option.device == "npu":
  148. config.enable_custom_device("npu")
  149. elif self.option.device == "xpu":
  150. pass
  151. elif self.option.device == "mlu":
  152. config.enable_custom_device("mlu")
  153. elif self.option.device == "gcu":
  154. assert paddle.device.is_compiled_with_custom_device("gcu"), (
  155. "Args device cannot be set as gcu while your paddle "
  156. "is not compiled with gcu!"
  157. )
  158. config.enable_custom_device("gcu")
  159. from paddle_custom_device.gcu import passes as gcu_passes
  160. gcu_passes.setUp()
  161. name = "PaddleX_" + self.option.model_name
  162. if hasattr(config, "enable_new_ir") and self.option.enable_new_ir:
  163. config.enable_new_ir(True)
  164. config.enable_new_executor(True)
  165. kPirGcuPasses = gcu_passes.inference_passes(use_pir=True, name=name)
  166. config.enable_custom_passes(kPirGcuPasses, True)
  167. else:
  168. config.enable_new_ir(False)
  169. config.enable_new_executor(False)
  170. pass_builder = config.pass_builder()
  171. gcu_passes.append_passes_for_legacy_ir(pass_builder, name)
  172. else:
  173. assert self.option.device == "cpu"
  174. config.disable_gpu()
  175. if "mkldnn" in self.option.run_mode:
  176. try:
  177. config.enable_mkldnn()
  178. if "bf16" in self.option.run_mode:
  179. config.enable_mkldnn_bfloat16()
  180. except Exception as e:
  181. logging.warning(
  182. "MKL-DNN is not available. We will disable MKL-DNN."
  183. )
  184. config.set_mkldnn_cache_capacity(-1)
  185. else:
  186. if hasattr(config, "disable_mkldnn"):
  187. config.disable_mkldnn()
  188. # Disable paddle inference logging
  189. config.disable_glog_info()
  190. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  191. if not (self.option.device == "gpu" and self.option.run_mode.startswith("trt")):
  192. if self.option.device in ("cpu", "gpu"):
  193. if hasattr(config, "enable_new_ir"):
  194. config.enable_new_ir(self.option.enable_new_ir)
  195. config.set_optimization_level(3)
  196. if hasattr(config, "enable_new_executor"):
  197. config.enable_new_executor()
  198. for del_p in self.option.delete_pass:
  199. config.delete_pass(del_p)
  200. if self.option.device in ("gpu", "dcu"):
  201. if paddle.is_compiled_with_rocm():
  202. # Delete unsupported passes in dcu
  203. config.delete_pass("conv2d_add_act_fuse_pass")
  204. config.delete_pass("conv2d_add_fuse_pass")
  205. predictor = create_predictor(config)
  206. # Get input and output handlers
  207. input_names = predictor.get_input_names()
  208. input_names.sort()
  209. input_handlers = []
  210. output_handlers = []
  211. for input_name in input_names:
  212. input_handler = predictor.get_input_handle(input_name)
  213. input_handlers.append(input_handler)
  214. output_names = predictor.get_output_names()
  215. for output_name in output_names:
  216. output_handler = predictor.get_output_handle(output_name)
  217. output_handlers.append(output_handler)
  218. return predictor, input_handlers, output_handlers
  219. def apply(self, **kwargs):
  220. if self.option.changed:
  221. self._reset()
  222. batches = self.to_batch(**kwargs)
  223. self.copy2gpu.apply(batches)
  224. self.infer.apply()
  225. pred = self.copy2cpu.apply()
  226. return self.format_output(pred)
  227. @property
  228. def sub_cmps(self):
  229. return {
  230. "Copy2GPU": self.copy2gpu,
  231. "Infer": self.infer,
  232. "Copy2CPU": self.copy2cpu,
  233. }
  234. @abstractmethod
  235. def to_batch(self):
  236. raise NotImplementedError
  237. @abstractmethod
  238. def format_output(self, pred):
  239. return [{"pred": res} for res in zip(*pred)]
  240. class ImagePredictor(BasePaddlePredictor):
  241. INPUT_KEYS = "img"
  242. OUTPUT_KEYS = "pred"
  243. DEAULT_INPUTS = {"img": "img"}
  244. DEAULT_OUTPUTS = {"pred": "pred"}
  245. def to_batch(self, img):
  246. return [np.stack(img, axis=0).astype(dtype=np.float32, copy=False)]
  247. def format_output(self, pred):
  248. return [{"pred": res} for res in zip(*pred)]
  249. class ImageDetPredictor(BasePaddlePredictor):
  250. INPUT_KEYS = [
  251. ["img", "scale_factors"],
  252. ["img", "scale_factors", "img_size"],
  253. ["img", "img_size"],
  254. ]
  255. OUTPUT_KEYS = [["boxes"], ["boxes", "masks"]]
  256. DEAULT_INPUTS = {"img": "img", "scale_factors": "scale_factors"}
  257. DEAULT_OUTPUTS = None
  258. def to_batch(self, img, scale_factors=[[1.0, 1.0]], img_size=None):
  259. scale_factors = [scale_factor[::-1] for scale_factor in scale_factors]
  260. if img_size is None:
  261. return [
  262. np.stack(img, axis=0).astype(dtype=np.float32, copy=False),
  263. np.stack(scale_factors, axis=0).astype(dtype=np.float32, copy=False),
  264. ]
  265. else:
  266. img_size = [img_size[::-1] for img_size in img_size]
  267. return [
  268. np.stack(img_size, axis=0).astype(dtype=np.float32, copy=False),
  269. np.stack(img, axis=0).astype(dtype=np.float32, copy=False),
  270. np.stack(scale_factors, axis=0).astype(dtype=np.float32, copy=False),
  271. ]
  272. def format_output(self, pred):
  273. box_idx_start = 0
  274. pred_box = []
  275. if len(pred) == 4:
  276. # Adapt to SOLOv2
  277. pred_class_id = []
  278. pred_mask = []
  279. pred_class_id.append([pred[1], pred[2]])
  280. pred_mask.append(pred[3])
  281. return [
  282. {
  283. "class_id": np.array(pred_class_id[i]),
  284. "masks": np.array(pred_mask[i]),
  285. }
  286. for i in range(len(pred_class_id))
  287. ]
  288. if len(pred) == 3:
  289. # Adapt to Instance Segmentation
  290. pred_mask = []
  291. for idx in range(len(pred[1])):
  292. np_boxes_num = pred[1][idx]
  293. box_idx_end = box_idx_start + np_boxes_num
  294. np_boxes = pred[0][box_idx_start:box_idx_end]
  295. pred_box.append(np_boxes)
  296. if len(pred) == 3:
  297. np_masks = pred[2][box_idx_start:box_idx_end]
  298. pred_mask.append(np_masks)
  299. box_idx_start = box_idx_end
  300. if len(pred) == 3:
  301. return [
  302. {"boxes": np.array(pred_box[i]), "masks": np.array(pred_mask[i])}
  303. for i in range(len(pred_box))
  304. ]
  305. else:
  306. return [{"boxes": np.array(res)} for res in pred_box]
  307. class TSPPPredictor(BasePaddlePredictor):
  308. INPUT_KEYS = "ts"
  309. OUTPUT_KEYS = "pred"
  310. DEAULT_INPUTS = {"ts": "ts"}
  311. DEAULT_OUTPUTS = {"pred": "pred"}
  312. def to_batch(self, ts):
  313. n = len(ts[0])
  314. x = [np.stack([lst[i] for lst in ts], axis=0) for i in range(n)]
  315. return x
  316. def format_output(self, pred):
  317. return [{"pred": res} for res in zip(*pred)]