static_infer.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 abc
  15. import subprocess
  16. from os import PathLike
  17. from pathlib import Path
  18. from typing import List, Sequence, Union
  19. import numpy as np
  20. from ....utils import logging
  21. from ....utils.deps import class_requires_deps
  22. from ....utils.flags import DEBUG, USE_PIR_TRT
  23. from ...utils.benchmark import benchmark, set_inference_operations
  24. from ...utils.hpi import (
  25. HPIConfig,
  26. OMConfig,
  27. ONNXRuntimeConfig,
  28. OpenVINOConfig,
  29. TensorRTConfig,
  30. suggest_inference_backend_and_config,
  31. )
  32. from ...utils.model_paths import get_model_paths
  33. from ...utils.pp_option import PaddlePredictorOption
  34. from ...utils.trt_config import DISABLE_TRT_HALF_OPS_CONFIG
  35. CACHE_DIR = ".cache"
  36. INFERENCE_OPERATIONS = [
  37. "PaddleInferChainLegacy",
  38. "MultiBackendInfer",
  39. ]
  40. set_inference_operations(INFERENCE_OPERATIONS)
  41. # XXX: Better use Paddle Inference API to do this
  42. def _pd_dtype_to_np_dtype(pd_dtype):
  43. import paddle
  44. if pd_dtype == paddle.inference.DataType.FLOAT64:
  45. return np.float64
  46. elif pd_dtype == paddle.inference.DataType.FLOAT32:
  47. return np.float32
  48. elif pd_dtype == paddle.inference.DataType.INT64:
  49. return np.int64
  50. elif pd_dtype == paddle.inference.DataType.INT32:
  51. return np.int32
  52. elif pd_dtype == paddle.inference.DataType.UINT8:
  53. return np.uint8
  54. elif pd_dtype == paddle.inference.DataType.INT8:
  55. return np.int8
  56. else:
  57. raise TypeError(f"Unsupported data type: {pd_dtype}")
  58. # old trt
  59. def _collect_trt_shape_range_info(
  60. model_file,
  61. model_params,
  62. gpu_id,
  63. shape_range_info_path,
  64. dynamic_shapes,
  65. dynamic_shape_input_data,
  66. ):
  67. import paddle.inference
  68. dynamic_shape_input_data = dynamic_shape_input_data or {}
  69. config = paddle.inference.Config(model_file, model_params)
  70. config.enable_use_gpu(100, gpu_id)
  71. config.collect_shape_range_info(shape_range_info_path)
  72. # TODO: Add other needed options
  73. config.disable_glog_info()
  74. predictor = paddle.inference.create_predictor(config)
  75. input_names = predictor.get_input_names()
  76. for name in dynamic_shapes:
  77. if name not in input_names:
  78. raise ValueError(
  79. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  80. )
  81. for name in input_names:
  82. if name not in dynamic_shapes:
  83. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  84. for name in dynamic_shape_input_data:
  85. if name not in input_names:
  86. raise ValueError(
  87. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  88. )
  89. # It would be better to check if the shapes are valid.
  90. min_arrs, opt_arrs, max_arrs = {}, {}, {}
  91. for name, candidate_shapes in dynamic_shapes.items():
  92. # XXX: Currently we have no way to get the data type of the tensor
  93. # without creating an input handle.
  94. handle = predictor.get_input_handle(name)
  95. dtype = _pd_dtype_to_np_dtype(handle.type())
  96. min_shape, opt_shape, max_shape = candidate_shapes
  97. if name in dynamic_shape_input_data:
  98. min_arrs[name] = np.array(
  99. dynamic_shape_input_data[name][0], dtype=dtype
  100. ).reshape(min_shape)
  101. opt_arrs[name] = np.array(
  102. dynamic_shape_input_data[name][1], dtype=dtype
  103. ).reshape(opt_shape)
  104. max_arrs[name] = np.array(
  105. dynamic_shape_input_data[name][2], dtype=dtype
  106. ).reshape(max_shape)
  107. else:
  108. min_arrs[name] = np.ones(min_shape, dtype=dtype)
  109. opt_arrs[name] = np.ones(opt_shape, dtype=dtype)
  110. max_arrs[name] = np.ones(max_shape, dtype=dtype)
  111. # `opt_arrs` is used twice to ensure it is the most frequently used.
  112. for arrs in [min_arrs, opt_arrs, opt_arrs, max_arrs]:
  113. for name, arr in arrs.items():
  114. handle = predictor.get_input_handle(name)
  115. handle.reshape(arr.shape)
  116. handle.copy_from_cpu(arr)
  117. predictor.run()
  118. # HACK: The shape range info will be written to the file only when
  119. # `predictor` is garbage collected. It works in CPython, but it is
  120. # definitely a bad idea to count on the implementation-dependent behavior of
  121. # a garbage collector. Is there a more explicit and deterministic way to
  122. # handle this?
  123. # HACK: Manually delete the predictor to trigger its destructor, ensuring that the shape_range_info file would be saved.
  124. del predictor
  125. # pir trt
  126. def _convert_trt(
  127. trt_cfg_setting,
  128. pp_model_file,
  129. pp_params_file,
  130. trt_save_path,
  131. device_id,
  132. dynamic_shapes,
  133. dynamic_shape_input_data,
  134. ):
  135. import paddle.inference
  136. from paddle.tensorrt.export import Input, TensorRTConfig, convert
  137. def _set_trt_config():
  138. for attr_name in trt_cfg_setting:
  139. assert hasattr(
  140. trt_config, attr_name
  141. ), f"The `{type(trt_config)}` don't have the attribute `{attr_name}`!"
  142. setattr(trt_config, attr_name, trt_cfg_setting[attr_name])
  143. def _get_predictor(model_file, params_file):
  144. # HACK
  145. config = paddle.inference.Config(str(model_file), str(params_file))
  146. config.enable_use_gpu(100, device_id)
  147. # NOTE: Disable oneDNN to circumvent a bug in Paddle Inference
  148. config.disable_mkldnn()
  149. config.disable_glog_info()
  150. return paddle.inference.create_predictor(config)
  151. dynamic_shape_input_data = dynamic_shape_input_data or {}
  152. predictor = _get_predictor(pp_model_file, pp_params_file)
  153. input_names = predictor.get_input_names()
  154. for name in dynamic_shapes:
  155. if name not in input_names:
  156. raise ValueError(
  157. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  158. )
  159. for name in input_names:
  160. if name not in dynamic_shapes:
  161. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  162. for name in dynamic_shape_input_data:
  163. if name not in input_names:
  164. raise ValueError(
  165. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  166. )
  167. trt_inputs = []
  168. for name, candidate_shapes in dynamic_shapes.items():
  169. # XXX: Currently we have no way to get the data type of the tensor
  170. # without creating an input handle.
  171. handle = predictor.get_input_handle(name)
  172. dtype = _pd_dtype_to_np_dtype(handle.type())
  173. min_shape, opt_shape, max_shape = candidate_shapes
  174. if name in dynamic_shape_input_data:
  175. min_arr = np.array(dynamic_shape_input_data[name][0], dtype=dtype).reshape(
  176. min_shape
  177. )
  178. opt_arr = np.array(dynamic_shape_input_data[name][1], dtype=dtype).reshape(
  179. opt_shape
  180. )
  181. max_arr = np.array(dynamic_shape_input_data[name][2], dtype=dtype).reshape(
  182. max_shape
  183. )
  184. else:
  185. min_arr = np.ones(min_shape, dtype=dtype)
  186. opt_arr = np.ones(opt_shape, dtype=dtype)
  187. max_arr = np.ones(max_shape, dtype=dtype)
  188. # refer to: https://github.com/PolaKuma/Paddle/blob/3347f225bc09f2ec09802a2090432dd5cb5b6739/test/tensorrt/test_converter_model_resnet50.py
  189. trt_input = Input((min_arr, opt_arr, max_arr))
  190. trt_inputs.append(trt_input)
  191. # Create TensorRTConfig
  192. trt_config = TensorRTConfig(inputs=trt_inputs)
  193. _set_trt_config()
  194. trt_config.save_model_dir = str(trt_save_path)
  195. pp_model_path = str(pp_model_file.with_suffix(""))
  196. convert(pp_model_path, trt_config)
  197. def _sort_inputs(inputs, names):
  198. # NOTE: Adjust input tensors to match the sorted sequence.
  199. indices = sorted(range(len(names)), key=names.__getitem__)
  200. inputs = [inputs[indices.index(i)] for i in range(len(inputs))]
  201. return inputs
  202. # FIXME: Name might be misleading
  203. @benchmark.timeit
  204. class PaddleInferChainLegacy:
  205. def __init__(self, predictor):
  206. self.predictor = predictor
  207. input_names = self.predictor.get_input_names()
  208. self.input_handles = []
  209. self.output_handles = []
  210. for input_name in input_names:
  211. input_handle = self.predictor.get_input_handle(input_name)
  212. self.input_handles.append(input_handle)
  213. output_names = self.predictor.get_output_names()
  214. for output_name in output_names:
  215. output_handle = self.predictor.get_output_handle(output_name)
  216. self.output_handles.append(output_handle)
  217. def __call__(self, x):
  218. for input_, input_handle in zip(x, self.input_handles):
  219. input_handle.reshape(input_.shape)
  220. input_handle.copy_from_cpu(input_)
  221. self.predictor.run()
  222. outputs = [o.copy_to_cpu() for o in self.output_handles]
  223. return outputs
  224. class StaticInfer(metaclass=abc.ABCMeta):
  225. @abc.abstractmethod
  226. def __call__(self, x: Sequence[np.ndarray]) -> List[np.ndarray]:
  227. raise NotImplementedError
  228. class PaddleInfer(StaticInfer):
  229. def __init__(
  230. self,
  231. model_dir: Union[str, PathLike],
  232. model_file_prefix: str,
  233. option: PaddlePredictorOption,
  234. ) -> None:
  235. super().__init__()
  236. self.model_dir = Path(model_dir)
  237. self.model_file_prefix = model_file_prefix
  238. self._option = option
  239. self.predictor = self._create()
  240. self.infer = PaddleInferChainLegacy(self.predictor)
  241. def __call__(self, x: Sequence[np.ndarray]) -> List[np.ndarray]:
  242. names = self.predictor.get_input_names()
  243. if len(names) != len(x):
  244. raise ValueError(
  245. f"The number of inputs does not match the model: {len(names)} vs {len(x)}"
  246. )
  247. # TODO:
  248. # Ensure that input tensors follow the model's input sequence without sorting.
  249. x = _sort_inputs(x, names)
  250. x = list(map(np.ascontiguousarray, x))
  251. pred = self.infer(x)
  252. return pred
  253. def _create(
  254. self,
  255. ):
  256. """_create"""
  257. import paddle
  258. import paddle.inference
  259. model_paths = get_model_paths(self.model_dir, self.model_file_prefix)
  260. if "paddle" not in model_paths:
  261. raise RuntimeError("No valid PaddlePaddle model found")
  262. model_file, params_file = model_paths["paddle"]
  263. if (
  264. self._option.model_name == "LaTeX_OCR_rec"
  265. and self._option.device_type == "cpu"
  266. ):
  267. import cpuinfo
  268. if (
  269. "GenuineIntel" in cpuinfo.get_cpu_info().get("vendor_id_raw", "")
  270. and self._option.run_mode != "mkldnn"
  271. ):
  272. logging.warning(
  273. "Now, the `LaTeX_OCR_rec` model only support `mkldnn` mode when running on Intel CPU devices. So using `mkldnn` instead."
  274. )
  275. self._option.run_mode = "mkldnn"
  276. logging.debug("`run_mode` updated to 'mkldnn'")
  277. if self._option.device_type == "cpu" and self._option.device_id is not None:
  278. self._option.device_id = None
  279. logging.debug("`device_id` has been set to None")
  280. if (
  281. self._option.device_type in ("gpu", "dcu", "npu", "mlu", "gcu", "xpu")
  282. and self._option.device_id is None
  283. ):
  284. self._option.device_id = 0
  285. logging.debug("`device_id` has been set to 0")
  286. # for TRT
  287. if self._option.run_mode.startswith("trt"):
  288. assert self._option.device_type == "gpu"
  289. cache_dir = self.model_dir / CACHE_DIR / "paddle"
  290. config = self._configure_trt(
  291. model_file,
  292. params_file,
  293. cache_dir,
  294. )
  295. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  296. config.enable_use_gpu(100, self._option.device_id)
  297. # for Native Paddle and MKLDNN
  298. else:
  299. config = paddle.inference.Config(str(model_file), str(params_file))
  300. if self._option.device_type == "gpu":
  301. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  302. from paddle.inference import PrecisionType
  303. precision = (
  304. PrecisionType.Half
  305. if self._option.run_mode == "paddle_fp16"
  306. else PrecisionType.Float32
  307. )
  308. config.enable_use_gpu(100, self._option.device_id, precision)
  309. if hasattr(config, "enable_new_ir"):
  310. config.enable_new_ir(self._option.enable_new_ir)
  311. if self._option.enable_new_ir and self._option.enable_cinn:
  312. config.enable_cinn()
  313. if hasattr(config, "enable_new_executor"):
  314. config.enable_new_executor()
  315. config.set_optimization_level(3)
  316. elif self._option.device_type == "npu":
  317. config.enable_custom_device("npu", self._option.device_id)
  318. if hasattr(config, "enable_new_ir"):
  319. config.enable_new_ir(self._option.enable_new_ir)
  320. if hasattr(config, "enable_new_executor"):
  321. config.enable_new_executor()
  322. elif self._option.device_type == "xpu":
  323. config.enable_xpu()
  324. config.set_xpu_device_id(self._option.device_id)
  325. if hasattr(config, "enable_new_ir"):
  326. config.enable_new_ir(self._option.enable_new_ir)
  327. if hasattr(config, "enable_new_executor"):
  328. config.enable_new_executor()
  329. config.delete_pass("conv2d_bn_xpu_fuse_pass")
  330. config.delete_pass("transfer_layout_pass")
  331. elif self._option.device_type == "mlu":
  332. config.enable_custom_device("mlu", self._option.device_id)
  333. if hasattr(config, "enable_new_ir"):
  334. config.enable_new_ir(self._option.enable_new_ir)
  335. if hasattr(config, "enable_new_executor"):
  336. config.enable_new_executor()
  337. elif self._option.device_type == "gcu":
  338. from paddle_custom_device.gcu import passes as gcu_passes
  339. gcu_passes.setUp()
  340. config.enable_custom_device("gcu", self._option.device_id)
  341. if hasattr(config, "enable_new_ir"):
  342. config.enable_new_ir()
  343. if hasattr(config, "enable_new_executor"):
  344. config.enable_new_executor()
  345. else:
  346. pass_builder = config.pass_builder()
  347. name = "PaddleX_" + self._option.model_name
  348. gcu_passes.append_passes_for_legacy_ir(pass_builder, name)
  349. elif self._option.device_type == "dcu":
  350. if hasattr(config, "enable_new_ir"):
  351. config.enable_new_ir(self._option.enable_new_ir)
  352. config.enable_use_gpu(100, self._option.device_id)
  353. if hasattr(config, "enable_new_executor"):
  354. config.enable_new_executor()
  355. # XXX: is_compiled_with_rocm() must be True on dcu platform ?
  356. if paddle.is_compiled_with_rocm():
  357. # Delete unsupported passes in dcu
  358. config.delete_pass("conv2d_add_act_fuse_pass")
  359. config.delete_pass("conv2d_add_fuse_pass")
  360. else:
  361. assert self._option.device_type == "cpu"
  362. config.disable_gpu()
  363. if "mkldnn" in self._option.run_mode:
  364. try:
  365. config.enable_mkldnn()
  366. if "bf16" in self._option.run_mode:
  367. config.enable_mkldnn_bfloat16()
  368. except Exception:
  369. logging.warning(
  370. "MKL-DNN is not available. We will disable MKL-DNN."
  371. )
  372. config.set_mkldnn_cache_capacity(-1)
  373. else:
  374. if hasattr(config, "disable_mkldnn"):
  375. config.disable_mkldnn()
  376. config.set_cpu_math_library_num_threads(self._option.cpu_threads)
  377. if hasattr(config, "enable_new_ir"):
  378. config.enable_new_ir(self._option.enable_new_ir)
  379. if hasattr(config, "enable_new_executor"):
  380. config.enable_new_executor()
  381. config.set_optimization_level(3)
  382. config.enable_memory_optim()
  383. for del_p in self._option.delete_pass:
  384. config.delete_pass(del_p)
  385. # Disable paddle inference logging
  386. if not DEBUG:
  387. config.disable_glog_info()
  388. predictor = paddle.inference.create_predictor(config)
  389. return predictor
  390. def _configure_trt(self, model_file, params_file, cache_dir):
  391. # TODO: Support calibration
  392. import paddle.inference
  393. if USE_PIR_TRT:
  394. if self._option.trt_dynamic_shapes is None:
  395. raise RuntimeError("No dynamic shape information provided")
  396. trt_save_path = cache_dir / "trt" / self.model_file_prefix
  397. trt_model_file = trt_save_path.with_suffix(".json")
  398. trt_params_file = trt_save_path.with_suffix(".pdiparams")
  399. if not trt_model_file.exists() or not trt_params_file.exists():
  400. _convert_trt(
  401. self._option.trt_cfg_setting,
  402. model_file,
  403. params_file,
  404. trt_save_path,
  405. self._option.device_id,
  406. self._option.trt_dynamic_shapes,
  407. self._option.trt_dynamic_shape_input_data,
  408. )
  409. else:
  410. logging.debug(
  411. f"Use TRT cache files(`{trt_model_file}` and `{trt_params_file}`)."
  412. )
  413. config = paddle.inference.Config(str(trt_model_file), str(trt_params_file))
  414. else:
  415. config = paddle.inference.Config(str(model_file), str(params_file))
  416. config.set_optim_cache_dir(str(cache_dir / "optim_cache"))
  417. # call enable_use_gpu() first to use TensorRT engine
  418. config.enable_use_gpu(100, self._option.device_id)
  419. for func_name in self._option.trt_cfg_setting:
  420. assert hasattr(
  421. config, func_name
  422. ), f"The `{type(config)}` don't have function `{func_name}`!"
  423. args = self._option.trt_cfg_setting[func_name]
  424. if isinstance(args, list):
  425. getattr(config, func_name)(*args)
  426. else:
  427. getattr(config, func_name)(**args)
  428. if self._option.trt_use_dynamic_shapes:
  429. if self._option.trt_dynamic_shapes is None:
  430. raise RuntimeError("No dynamic shape information provided")
  431. if self._option.trt_collect_shape_range_info:
  432. # NOTE: We always use a shape range info file.
  433. if self._option.trt_shape_range_info_path is not None:
  434. trt_shape_range_info_path = Path(
  435. self._option.trt_shape_range_info_path
  436. )
  437. else:
  438. trt_shape_range_info_path = cache_dir / "shape_range_info.pbtxt"
  439. should_collect_shape_range_info = True
  440. if not trt_shape_range_info_path.exists():
  441. trt_shape_range_info_path.parent.mkdir(
  442. parents=True, exist_ok=True
  443. )
  444. logging.info(
  445. f"Shape range info will be collected into {trt_shape_range_info_path}"
  446. )
  447. elif self._option.trt_discard_cached_shape_range_info:
  448. trt_shape_range_info_path.unlink()
  449. logging.info(
  450. f"The shape range info file ({trt_shape_range_info_path}) has been removed, and the shape range info will be re-collected."
  451. )
  452. else:
  453. logging.info(
  454. f"A shape range info file ({trt_shape_range_info_path}) already exists. There is no need to collect the info again."
  455. )
  456. should_collect_shape_range_info = False
  457. if should_collect_shape_range_info:
  458. _collect_trt_shape_range_info(
  459. str(model_file),
  460. str(params_file),
  461. self._option.device_id,
  462. str(trt_shape_range_info_path),
  463. self._option.trt_dynamic_shapes,
  464. self._option.trt_dynamic_shape_input_data,
  465. )
  466. if (
  467. self._option.model_name in DISABLE_TRT_HALF_OPS_CONFIG
  468. and self._option.run_mode == "trt_fp16"
  469. ):
  470. paddle.inference.InternalUtils.disable_tensorrt_half_ops(
  471. config, DISABLE_TRT_HALF_OPS_CONFIG[self._option.model_name]
  472. )
  473. config.enable_tuned_tensorrt_dynamic_shape(
  474. str(trt_shape_range_info_path),
  475. self._option.trt_allow_rebuild_at_runtime,
  476. )
  477. else:
  478. min_shapes, opt_shapes, max_shapes = {}, {}, {}
  479. for (
  480. key,
  481. shapes,
  482. ) in self._option.trt_dynamic_shapes.items():
  483. min_shapes[key] = shapes[0]
  484. opt_shapes[key] = shapes[1]
  485. max_shapes[key] = shapes[2]
  486. config.set_trt_dynamic_shape_info(
  487. min_shapes, max_shapes, opt_shapes
  488. )
  489. return config
  490. # FIXME: Name might be misleading
  491. @benchmark.timeit
  492. @class_requires_deps("ultra-infer")
  493. class MultiBackendInfer(object):
  494. def __init__(self, ui_runtime):
  495. super().__init__()
  496. self.ui_runtime = ui_runtime
  497. # The time consumed by the wrapper code will also be taken into account.
  498. def __call__(self, x):
  499. outputs = self.ui_runtime.infer(x)
  500. return outputs
  501. # TODO: It would be better to refactor the code to make `HPInfer` a higher-level
  502. # class that uses `PaddleInfer`.
  503. @class_requires_deps("ultra-infer")
  504. class HPInfer(StaticInfer):
  505. def __init__(
  506. self,
  507. model_dir: Union[str, PathLike],
  508. model_file_prefix: str,
  509. config: HPIConfig,
  510. ) -> None:
  511. super().__init__()
  512. self._model_dir = Path(model_dir)
  513. self._model_file_prefix = model_file_prefix
  514. self._config = config
  515. backend, backend_config = self._determine_backend_and_config()
  516. if backend == "paddle":
  517. self._use_paddle = True
  518. self._paddle_infer = self._build_paddle_infer(backend_config)
  519. else:
  520. self._use_paddle = False
  521. ui_runtime = self._build_ui_runtime(backend, backend_config)
  522. self._multi_backend_infer = MultiBackendInfer(ui_runtime)
  523. num_inputs = ui_runtime.num_inputs()
  524. self._input_names = [
  525. ui_runtime.get_input_info(i).name for i in range(num_inputs)
  526. ]
  527. @property
  528. def model_dir(self) -> Path:
  529. return self._model_dir
  530. @property
  531. def model_file_prefix(self) -> str:
  532. return self._model_file_prefix
  533. @property
  534. def config(self) -> HPIConfig:
  535. return self._config
  536. def __call__(self, x: Sequence[np.ndarray]) -> List[np.ndarray]:
  537. if self._use_paddle:
  538. return self._call_paddle_infer(x)
  539. else:
  540. return self._call_multi_backend_infer(x)
  541. def _call_paddle_infer(self, x):
  542. return self._paddle_infer(x)
  543. def _call_multi_backend_infer(self, x):
  544. num_inputs = len(self._input_names)
  545. if len(x) != num_inputs:
  546. raise ValueError(f"Expected {num_inputs} inputs but got {len(x)} instead")
  547. x = _sort_inputs(x, self._input_names)
  548. inputs = {}
  549. for name, input_ in zip(self._input_names, x):
  550. inputs[name] = np.ascontiguousarray(input_)
  551. return self._multi_backend_infer(inputs)
  552. def _determine_backend_and_config(self):
  553. if self._config.auto_config:
  554. # Should we use the strategy pattern here to allow extensible
  555. # strategies?
  556. model_paths = get_model_paths(self._model_dir, self._model_file_prefix)
  557. ret = suggest_inference_backend_and_config(
  558. self._config,
  559. model_paths,
  560. )
  561. if ret[0] is None:
  562. # Should I use a custom exception?
  563. raise RuntimeError(
  564. f"No inference backend and configuration could be suggested. Reason: {ret[1]}"
  565. )
  566. backend, backend_config = ret
  567. else:
  568. backend = self._config.backend
  569. if backend is None:
  570. raise RuntimeError(
  571. "When automatic configuration is not used, the inference backend must be specified manually."
  572. )
  573. backend_config = self._config.backend_config or {}
  574. if backend == "paddle" and not backend_config:
  575. logging.warning(
  576. "The Paddle Inference backend is selected with the default configuration. This may not provide optimal performance."
  577. )
  578. return backend, backend_config
  579. def _build_paddle_infer(self, backend_config):
  580. kwargs = {
  581. "device_type": self._config.device_type,
  582. "device_id": self._config.device_id,
  583. **backend_config,
  584. }
  585. # TODO: This is probably redundant. Can we reuse the code in the
  586. # predictor class?
  587. paddle_info = None
  588. if self._config.hpi_info:
  589. hpi_info = self._config.hpi_info
  590. if hpi_info.backend_configs:
  591. paddle_info = hpi_info.backend_configs.paddle_infer
  592. if paddle_info is not None:
  593. if (
  594. kwargs.get("trt_dynamic_shapes") is None
  595. and paddle_info.trt_dynamic_shapes is not None
  596. ):
  597. trt_dynamic_shapes = paddle_info.trt_dynamic_shapes
  598. logging.debug("TensorRT dynamic shapes set to %s", trt_dynamic_shapes)
  599. kwargs["trt_dynamic_shapes"] = trt_dynamic_shapes
  600. if (
  601. kwargs.get("trt_dynamic_shape_input_data") is None
  602. and paddle_info.trt_dynamic_shape_input_data is not None
  603. ):
  604. trt_dynamic_shape_input_data = paddle_info.trt_dynamic_shape_input_data
  605. logging.debug(
  606. "TensorRT dynamic shape input data set to %s",
  607. trt_dynamic_shape_input_data,
  608. )
  609. kwargs["trt_dynamic_shape_input_data"] = trt_dynamic_shape_input_data
  610. pp_option = PaddlePredictorOption(self._config.pdx_model_name, **kwargs)
  611. logging.info("Using Paddle Inference backend")
  612. logging.info("Paddle predictor option: %s", pp_option)
  613. return PaddleInfer(self._model_dir, self._model_file_prefix, option=pp_option)
  614. def _build_ui_runtime(self, backend, backend_config, ui_option=None):
  615. from ultra_infer import ModelFormat, Runtime, RuntimeOption
  616. if ui_option is None:
  617. ui_option = RuntimeOption()
  618. if self._config.device_type == "cpu":
  619. pass
  620. elif self._config.device_type == "gpu":
  621. ui_option.use_gpu(self._config.device_id or 0)
  622. elif self._config.device_type == "npu":
  623. ui_option.use_ascend(self._config.device_id or 0)
  624. else:
  625. raise RuntimeError(
  626. f"Unsupported device type {repr(self._config.device_type)}"
  627. )
  628. model_paths = get_model_paths(self._model_dir, self.model_file_prefix)
  629. if backend in ("openvino", "onnxruntime", "tensorrt"):
  630. # XXX: This introduces side effects.
  631. if "onnx" not in model_paths:
  632. if self._config.auto_paddle2onnx:
  633. if "paddle" not in model_paths:
  634. raise RuntimeError("PaddlePaddle model required")
  635. # The CLI is used here since there is currently no API.
  636. logging.info(
  637. "Automatically converting PaddlePaddle model to ONNX format"
  638. )
  639. try:
  640. subprocess.run(
  641. [
  642. "paddlex",
  643. "--paddle2onnx",
  644. "--paddle_model_dir",
  645. str(self._model_dir),
  646. "--onnx_model_dir",
  647. str(self._model_dir),
  648. ],
  649. capture_output=True,
  650. check=True,
  651. text=True,
  652. )
  653. except subprocess.CalledProcessError as e:
  654. raise RuntimeError(
  655. f"PaddlePaddle-to-ONNX conversion failed:\n{e.stderr}"
  656. ) from e
  657. model_paths = get_model_paths(
  658. self._model_dir, self.model_file_prefix
  659. )
  660. assert "onnx" in model_paths
  661. else:
  662. raise RuntimeError("ONNX model required")
  663. ui_option.set_model_path(str(model_paths["onnx"]), "", ModelFormat.ONNX)
  664. elif backend == "om":
  665. if "om" not in model_paths:
  666. raise RuntimeError("OM model required")
  667. ui_option.set_model_path(str(model_paths["om"]), "", ModelFormat.OM)
  668. else:
  669. raise ValueError(f"Unsupported inference backend {repr(backend)}")
  670. if backend == "openvino":
  671. backend_config = OpenVINOConfig.model_validate(backend_config)
  672. ui_option.use_openvino_backend()
  673. ui_option.set_cpu_thread_num(backend_config.cpu_num_threads)
  674. elif backend == "onnxruntime":
  675. backend_config = ONNXRuntimeConfig.model_validate(backend_config)
  676. ui_option.use_ort_backend()
  677. ui_option.set_cpu_thread_num(backend_config.cpu_num_threads)
  678. elif backend == "tensorrt":
  679. if (
  680. backend_config.get("use_dynamic_shapes", True)
  681. and backend_config.get("dynamic_shapes") is None
  682. ):
  683. trt_info = None
  684. if self._config.hpi_info:
  685. hpi_info = self._config.hpi_info
  686. if hpi_info.backend_configs:
  687. trt_info = hpi_info.backend_configs.tensorrt
  688. if trt_info is not None and trt_info.dynamic_shapes is not None:
  689. trt_dynamic_shapes = trt_info.dynamic_shapes
  690. logging.debug(
  691. "TensorRT dynamic shapes set to %s", trt_dynamic_shapes
  692. )
  693. backend_config = {
  694. **backend_config,
  695. "dynamic_shapes": trt_dynamic_shapes,
  696. }
  697. backend_config = TensorRTConfig.model_validate(backend_config)
  698. ui_option.use_trt_backend()
  699. cache_dir = self._model_dir / CACHE_DIR / "tensorrt"
  700. cache_dir.mkdir(parents=True, exist_ok=True)
  701. ui_option.trt_option.serialize_file = str(cache_dir / "trt_serialized.trt")
  702. if backend_config.precision == "fp16":
  703. ui_option.trt_option.enable_fp16 = True
  704. if not backend_config.use_dynamic_shapes:
  705. raise RuntimeError(
  706. "TensorRT static shape inference is currently not supported"
  707. )
  708. if backend_config.dynamic_shapes is not None:
  709. if not Path(ui_option.trt_option.serialize_file).exists():
  710. for name, shapes in backend_config.dynamic_shapes.items():
  711. ui_option.trt_option.set_shape(name, *shapes)
  712. else:
  713. logging.info(
  714. "TensorRT dynamic shapes will be loaded from the file."
  715. )
  716. elif backend == "om":
  717. backend_config = OMConfig.model_validate(backend_config)
  718. ui_option.use_om_backend()
  719. else:
  720. raise ValueError(f"Unsupported inference backend {repr(backend)}")
  721. logging.info("Inference backend: %s", backend)
  722. logging.info("Inference backend config: %s", backend_config)
  723. ui_runtime = Runtime(ui_option)
  724. return ui_runtime