predictor.py 9.7 KB

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