static_infer.py 33 KB

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