predictor.py 11 KB

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