static_infer.py 34 KB

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