predictor.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. class BasePaddlePredictor(BaseComponent):
  23. """Predictor based on Paddle Inference"""
  24. OUTPUT_KEYS = "pred"
  25. DEAULT_OUTPUTS = {"pred": "pred"}
  26. ENABLE_BATCH = True
  27. def __init__(self, model_dir, model_prefix, option):
  28. super().__init__()
  29. self.model_dir = model_dir
  30. self.model_prefix = model_prefix
  31. self._update_option(option)
  32. def _update_option(self, option):
  33. if option:
  34. if self.option and option == self.option:
  35. return
  36. self._option = option
  37. self._reset()
  38. @property
  39. def option(self):
  40. return self._option if hasattr(self, "_option") else None
  41. @option.setter
  42. def option(self, option):
  43. self._update_option(option)
  44. def _reset(self):
  45. if not self.option:
  46. self.option = PaddlePredictorOption()
  47. logging.debug(f"Env: {self.option}")
  48. (
  49. self.predictor,
  50. self.inference_config,
  51. self.input_names,
  52. self.input_handlers,
  53. self.output_handlers,
  54. ) = self._create()
  55. self.option.changed = False
  56. def _create(self):
  57. """_create"""
  58. from lazy_paddle.inference import Config, create_predictor
  59. model_postfix = ".json" if FLAGS_json_format_model else ".pdmodel"
  60. model_file = (self.model_dir / f"{self.model_prefix}{model_postfix}").as_posix()
  61. params_file = (self.model_dir / f"{self.model_prefix}.pdiparams").as_posix()
  62. config = Config(model_file, params_file)
  63. config.enable_memory_optim()
  64. if self.option.device in ("gpu", "dcu"):
  65. if self.option.device == "gpu":
  66. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  67. config.enable_use_gpu(100, self.option.device_id)
  68. if self.option.device == "gpu":
  69. # NOTE: The pptrt settings are not aligned with those of FD.
  70. precision_map = {
  71. "trt_int8": Config.Precision.Int8,
  72. "trt_fp32": Config.Precision.Float32,
  73. "trt_fp16": Config.Precision.Half,
  74. }
  75. if self.option.run_mode in precision_map.keys():
  76. config.enable_tensorrt_engine(
  77. workspace_size=(1 << 25) * self.option.batch_size,
  78. max_batch_size=self.option.batch_size,
  79. min_subgraph_size=self.option.min_subgraph_size,
  80. precision_mode=precision_map[self.option.run_mode],
  81. use_static=self.option.trt_use_static,
  82. use_calib_mode=self.option.trt_calib_mode,
  83. )
  84. if self.option.shape_info_filename is not None:
  85. if not os.path.exists(self.option.shape_info_filename):
  86. config.collect_shape_range_info(
  87. self.option.shape_info_filename
  88. )
  89. logging.info(
  90. f"Dynamic shape info is collected into: {self.option.shape_info_filename}"
  91. )
  92. else:
  93. logging.info(
  94. f"A dynamic shape info file ( {self.option.shape_info_filename} ) already exists. \
  95. No need to generate again."
  96. )
  97. config.enable_tuned_tensorrt_dynamic_shape(
  98. self.option.shape_info_filename, True
  99. )
  100. elif self.option.device == "npu":
  101. config.enable_custom_device("npu")
  102. elif self.option.device == "xpu":
  103. pass
  104. elif self.option.device == "mlu":
  105. config.enable_custom_device("mlu")
  106. else:
  107. assert self.option.device == "cpu"
  108. config.disable_gpu()
  109. if "mkldnn" in self.option.run_mode:
  110. try:
  111. config.enable_mkldnn()
  112. if "bf16" in self.option.run_mode:
  113. config.enable_mkldnn_bfloat16()
  114. except Exception as e:
  115. logging.warning(
  116. "MKL-DNN is not available. We will disable MKL-DNN."
  117. )
  118. config.set_mkldnn_cache_capacity(-1)
  119. else:
  120. if hasattr(config, "disable_mkldnn"):
  121. config.disable_mkldnn()
  122. # Disable paddle inference logging
  123. config.disable_glog_info()
  124. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  125. if not (self.option.device == "gpu" and self.option.run_mode.startswith("trt")):
  126. if hasattr(config, "enable_new_ir"):
  127. config.enable_new_ir(self.option.enable_new_ir)
  128. if hasattr(config, "enable_new_executor"):
  129. config.enable_new_executor()
  130. config.set_optimization_level(3)
  131. for del_p in self.option.delete_pass:
  132. config.delete_pass(del_p)
  133. if self.option.device in ("gpu", "dcu"):
  134. if paddle.is_compiled_with_rocm():
  135. # Delete unsupported passes in dcu
  136. config.delete_pass("conv2d_add_act_fuse_pass")
  137. config.delete_pass("conv2d_add_fuse_pass")
  138. predictor = create_predictor(config)
  139. # Get input and output handlers
  140. input_names = predictor.get_input_names()
  141. input_names.sort()
  142. input_handlers = []
  143. output_handlers = []
  144. for input_name in input_names:
  145. input_handler = predictor.get_input_handle(input_name)
  146. input_handlers.append(input_handler)
  147. output_names = predictor.get_output_names()
  148. for output_name in output_names:
  149. output_handler = predictor.get_output_handle(output_name)
  150. output_handlers.append(output_handler)
  151. return predictor, config, input_names, input_handlers, output_handlers
  152. def get_input_names(self):
  153. """get input names"""
  154. return self.input_names
  155. def apply(self, **kwargs):
  156. if self.option.changed:
  157. self._reset()
  158. x = self.to_batch(**kwargs)
  159. for idx in range(len(x)):
  160. self.input_handlers[idx].reshape(x[idx].shape)
  161. self.input_handlers[idx].copy_from_cpu(x[idx])
  162. self.predictor.run()
  163. output = []
  164. for out_tensor in self.output_handlers:
  165. batch = out_tensor.copy_to_cpu()
  166. output.append(batch)
  167. return self.format_output(output)
  168. def format_output(self, pred):
  169. return [{"pred": res} for res in zip(*pred)]
  170. @abstractmethod
  171. def to_batch(self):
  172. raise NotImplementedError
  173. class ImagePredictor(BasePaddlePredictor):
  174. INPUT_KEYS = "img"
  175. DEAULT_INPUTS = {"img": "img"}
  176. def to_batch(self, img):
  177. return [np.stack(img, axis=0).astype(dtype=np.float32, copy=False)]
  178. class ImageDetPredictor(BasePaddlePredictor):
  179. INPUT_KEYS = [
  180. ["img", "scale_factors"],
  181. ["img", "scale_factors", "img_size"],
  182. ["img", "img_size"],
  183. ]
  184. OUTPUT_KEYS = [["boxes"], ["boxes", "masks"]]
  185. DEAULT_INPUTS = {"img": "img", "scale_factors": "scale_factors"}
  186. DEAULT_OUTPUTS = None
  187. def to_batch(self, img, scale_factors=[[1.0, 1.0]], img_size=None):
  188. scale_factors = [scale_factor[::-1] for scale_factor in scale_factors]
  189. if img_size is None:
  190. return [
  191. np.stack(img, axis=0).astype(dtype=np.float32, copy=False),
  192. np.stack(scale_factors, axis=0).astype(dtype=np.float32, copy=False),
  193. ]
  194. else:
  195. img_size = [img_size[::-1] for img_size in img_size]
  196. return [
  197. np.stack(img_size, axis=0).astype(dtype=np.float32, copy=False),
  198. np.stack(img, axis=0).astype(dtype=np.float32, copy=False),
  199. np.stack(scale_factors, axis=0).astype(dtype=np.float32, copy=False),
  200. ]
  201. def format_output(self, pred):
  202. box_idx_start = 0
  203. pred_box = []
  204. if len(pred) == 4:
  205. # Adapt to SOLOv2
  206. pred_class_id = []
  207. pred_mask = []
  208. pred_class_id.append([pred[1], pred[2]])
  209. pred_mask.append(pred[3])
  210. return [
  211. {
  212. "class_id": np.array(pred_class_id[i]),
  213. "masks": np.array(pred_mask[i]),
  214. }
  215. for i in range(len(pred_class_id))
  216. ]
  217. if len(pred) == 3:
  218. # Adapt to Instance Segmentation
  219. pred_mask = []
  220. for idx in range(len(pred[1])):
  221. np_boxes_num = pred[1][idx]
  222. box_idx_end = box_idx_start + np_boxes_num
  223. np_boxes = pred[0][box_idx_start:box_idx_end]
  224. pred_box.append(np_boxes)
  225. if len(pred) == 3:
  226. np_masks = pred[2][box_idx_start:box_idx_end]
  227. pred_mask.append(np_masks)
  228. box_idx_start = box_idx_end
  229. if len(pred) == 3:
  230. return [
  231. {"boxes": np.array(pred_box[i]), "masks": np.array(pred_mask[i])}
  232. for i in range(len(pred_box))
  233. ]
  234. else:
  235. return [{"boxes": np.array(res)} for res in pred_box]
  236. class TSPPPredictor(BasePaddlePredictor):
  237. INPUT_KEYS = "ts"
  238. DEAULT_INPUTS = {"ts": "ts"}
  239. def to_batch(self, ts):
  240. n = len(ts[0])
  241. x = [np.stack([lst[i] for lst in ts], axis=0) for i in range(n)]
  242. return x