static_infer.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Sequence, List
  15. from pathlib import Path
  16. import lazy_paddle
  17. import numpy as np
  18. from ....utils import logging
  19. from ....utils.device import constr_device
  20. from ....utils.flags import (
  21. DEBUG,
  22. USE_PIR_TRT,
  23. INFER_BENCHMARK_USE_NEW_INFER_API,
  24. )
  25. from ...utils.benchmark import benchmark, set_inference_operations
  26. from ...utils.hpi import get_model_paths
  27. from ...utils.pp_option import PaddlePredictorOption
  28. CACHE_DIR = ".cache"
  29. if INFER_BENCHMARK_USE_NEW_INFER_API:
  30. INFERENCE_OPERATIONS = [
  31. "PaddleCopyToDevice",
  32. "PaddleCopyToHost",
  33. "PaddleModelInfer",
  34. ]
  35. else:
  36. INFERENCE_OPERATIONS = ["PaddleInferChainLegacy"]
  37. set_inference_operations(INFERENCE_OPERATIONS)
  38. # XXX: Better use Paddle Inference API to do this
  39. def _pd_dtype_to_np_dtype(pd_dtype):
  40. if pd_dtype == lazy_paddle.inference.DataType.FLOAT64:
  41. return np.float64
  42. elif pd_dtype == lazy_paddle.inference.DataType.FLOAT32:
  43. return np.float32
  44. elif pd_dtype == lazy_paddle.inference.DataType.INT64:
  45. return np.int64
  46. elif pd_dtype == lazy_paddle.inference.DataType.INT32:
  47. return np.int32
  48. elif pd_dtype == lazy_paddle.inference.DataType.UINT8:
  49. return np.uint8
  50. elif pd_dtype == lazy_paddle.inference.DataType.INT8:
  51. return np.int8
  52. else:
  53. raise TypeError(f"Unsupported data type: {pd_dtype}")
  54. # old trt
  55. def _collect_trt_shape_range_info(
  56. model_file,
  57. model_params,
  58. gpu_id,
  59. shape_range_info_path,
  60. dynamic_shapes,
  61. dynamic_shape_input_data,
  62. ):
  63. dynamic_shape_input_data = dynamic_shape_input_data or {}
  64. config = lazy_paddle.inference.Config(model_file, model_params)
  65. config.enable_use_gpu(100, gpu_id)
  66. config.collect_shape_range_info(shape_range_info_path)
  67. # TODO: Add other needed options
  68. config.disable_glog_info()
  69. predictor = lazy_paddle.inference.create_predictor(config)
  70. input_names = predictor.get_input_names()
  71. for name in dynamic_shapes:
  72. if name not in input_names:
  73. raise ValueError(
  74. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  75. )
  76. for name in input_names:
  77. if name not in dynamic_shapes:
  78. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  79. for name in dynamic_shape_input_data:
  80. if name not in input_names:
  81. raise ValueError(
  82. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  83. )
  84. # It would be better to check if the shapes are valid.
  85. min_arrs, opt_arrs, max_arrs = {}, {}, {}
  86. for name, candidate_shapes in dynamic_shapes.items():
  87. # XXX: Currently we have no way to get the data type of the tensor
  88. # without creating an input handle.
  89. handle = predictor.get_input_handle(name)
  90. dtype = _pd_dtype_to_np_dtype(handle.type())
  91. min_shape, opt_shape, max_shape = candidate_shapes
  92. if name in dynamic_shape_input_data:
  93. min_arrs[name] = np.array(
  94. dynamic_shape_input_data[name][0], dtype=dtype
  95. ).reshape(min_shape)
  96. opt_arrs[name] = np.array(
  97. dynamic_shape_input_data[name][1], dtype=dtype
  98. ).reshape(opt_shape)
  99. max_arrs[name] = np.array(
  100. dynamic_shape_input_data[name][2], dtype=dtype
  101. ).reshape(max_shape)
  102. else:
  103. min_arrs[name] = np.ones(min_shape, dtype=dtype)
  104. opt_arrs[name] = np.ones(opt_shape, dtype=dtype)
  105. max_arrs[name] = np.ones(max_shape, dtype=dtype)
  106. # `opt_arrs` is used twice to ensure it is the most frequently used.
  107. for arrs in [min_arrs, opt_arrs, opt_arrs, max_arrs]:
  108. for name, arr in arrs.items():
  109. handle = predictor.get_input_handle(name)
  110. handle.reshape(arr.shape)
  111. handle.copy_from_cpu(arr)
  112. predictor.run()
  113. # HACK: The shape range info will be written to the file only when
  114. # `predictor` is garbage collected. It works in CPython, but it is
  115. # definitely a bad idea to count on the implementation-dependent behavior of
  116. # a garbage collector. Is there a more explicit and deterministic way to
  117. # handle this?
  118. # HACK: Manually delete the predictor to trigger its destructor, ensuring that the shape_range_info file would be saved.
  119. del predictor
  120. # pir trt
  121. def _convert_trt(
  122. trt_cfg_setting,
  123. pp_model_file,
  124. pp_params_file,
  125. trt_save_path,
  126. device_id,
  127. dynamic_shapes,
  128. dynamic_shape_input_data,
  129. ):
  130. from lazy_paddle.tensorrt.export import (
  131. Input,
  132. TensorRTConfig,
  133. convert,
  134. )
  135. def _set_trt_config():
  136. for attr_name in trt_cfg_setting:
  137. assert hasattr(
  138. trt_config, attr_name
  139. ), f"The `{type(trt_config)}` don't have the attribute `{attr_name}`!"
  140. setattr(trt_config, attr_name, trt_cfg_setting[attr_name])
  141. def _get_predictor(model_file, params_file):
  142. # HACK
  143. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  144. config.enable_use_gpu(100, device_id)
  145. # NOTE: Disable oneDNN to circumvent a bug in Paddle Inference
  146. config.disable_mkldnn()
  147. config.disable_glog_info()
  148. return lazy_paddle.inference.create_predictor(config)
  149. dynamic_shape_input_data = dynamic_shape_input_data or {}
  150. predictor = _get_predictor(pp_model_file, pp_params_file)
  151. input_names = predictor.get_input_names()
  152. for name in dynamic_shapes:
  153. if name not in input_names:
  154. raise ValueError(
  155. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  156. )
  157. for name in input_names:
  158. if name not in dynamic_shapes:
  159. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  160. for name in dynamic_shape_input_data:
  161. if name not in input_names:
  162. raise ValueError(
  163. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  164. )
  165. trt_inputs = []
  166. for name, candidate_shapes in dynamic_shapes.items():
  167. # XXX: Currently we have no way to get the data type of the tensor
  168. # without creating an input handle.
  169. handle = predictor.get_input_handle(name)
  170. dtype = _pd_dtype_to_np_dtype(handle.type())
  171. min_shape, opt_shape, max_shape = candidate_shapes
  172. if name in dynamic_shape_input_data:
  173. min_arr = np.array(dynamic_shape_input_data[name][0], dtype=dtype).reshape(
  174. min_shape
  175. )
  176. opt_arr = np.array(dynamic_shape_input_data[name][1], dtype=dtype).reshape(
  177. opt_shape
  178. )
  179. max_arr = np.array(dynamic_shape_input_data[name][2], dtype=dtype).reshape(
  180. max_shape
  181. )
  182. else:
  183. min_arr = np.ones(min_shape, dtype=dtype)
  184. opt_arr = np.ones(opt_shape, dtype=dtype)
  185. max_arr = np.ones(max_shape, dtype=dtype)
  186. # refer to: https://github.com/PolaKuma/Paddle/blob/3347f225bc09f2ec09802a2090432dd5cb5b6739/test/tensorrt/test_converter_model_resnet50.py
  187. trt_input = Input((min_arr, opt_arr, max_arr))
  188. trt_inputs.append(trt_input)
  189. # Create TensorRTConfig
  190. trt_config = TensorRTConfig(inputs=trt_inputs)
  191. _set_trt_config()
  192. trt_config.save_model_dir = str(trt_save_path)
  193. pp_model_path = str(pp_model_file.with_suffix(""))
  194. convert(pp_model_path, trt_config)
  195. def _sort_inputs(inputs, names):
  196. # NOTE: Adjust input tensors to match the sorted sequence.
  197. indices = sorted(range(len(names)), key=names.__getitem__)
  198. inputs = [inputs[indices.index(i)] for i in range(len(inputs))]
  199. return inputs
  200. def _concatenate(*callables):
  201. def _chain(x):
  202. for c in callables:
  203. x = c(x)
  204. return x
  205. return _chain
  206. @benchmark.timeit
  207. class PaddleCopyToDevice:
  208. def __init__(self, device_type, device_id):
  209. self.device_type = device_type
  210. self.device_id = device_id
  211. def __call__(self, arrs):
  212. device_id = [self.device_id] if self.device_id is not None else self.device_id
  213. device = constr_device(self.device_type, device_id)
  214. paddle_tensors = [lazy_paddle.to_tensor(i, place=device) for i in arrs]
  215. return paddle_tensors
  216. @benchmark.timeit
  217. class PaddleCopyToHost:
  218. def __call__(self, paddle_tensors):
  219. arrs = [i.numpy() for i in paddle_tensors]
  220. return arrs
  221. @benchmark.timeit
  222. class PaddleModelInfer:
  223. def __init__(self, predictor):
  224. super().__init__()
  225. self.predictor = predictor
  226. def __call__(self, x):
  227. return self.predictor.run(x)
  228. # FIXME: Name might be misleading
  229. @benchmark.timeit
  230. class PaddleInferChainLegacy:
  231. def __init__(self, predictor):
  232. self.predictor = predictor
  233. input_names = self.predictor.get_input_names()
  234. self.input_handles = []
  235. self.output_handles = []
  236. for input_name in input_names:
  237. input_handle = self.predictor.get_input_handle(input_name)
  238. self.input_handles.append(input_handle)
  239. output_names = self.predictor.get_output_names()
  240. for output_name in output_names:
  241. output_handle = self.predictor.get_output_handle(output_name)
  242. self.output_handles.append(output_handle)
  243. def __call__(self, x):
  244. for input_, input_handle in zip(x, self.input_handles):
  245. input_handle.reshape(input_.shape)
  246. input_handle.copy_from_cpu(input_)
  247. self.predictor.run()
  248. outputs = [o.copy_to_cpu() for o in self.output_handles]
  249. return outputs
  250. class StaticInfer(object):
  251. def __init__(
  252. self,
  253. model_dir: str,
  254. model_prefix: str,
  255. option: PaddlePredictorOption,
  256. ) -> None:
  257. super().__init__()
  258. self.model_dir = model_dir
  259. self.model_file_prefix = model_prefix
  260. self._option = option
  261. self.predictor = self._create()
  262. if self._use_new_inference_api:
  263. device_type = self._option.device_type
  264. device_type = "gpu" if device_type == "dcu" else device_type
  265. copy_to_device = PaddleCopyToDevice(device_type, self._option.device_id)
  266. copy_to_host = PaddleCopyToHost()
  267. model_infer = PaddleModelInfer(self.predictor)
  268. self.infer = _concatenate(copy_to_device, model_infer, copy_to_host)
  269. else:
  270. self.infer = PaddleInferChainLegacy(self.predictor)
  271. @property
  272. def _use_new_inference_api(self):
  273. # HACK: Temp fallback to legacy API via env var
  274. return INFER_BENCHMARK_USE_NEW_INFER_API
  275. # return self._option.device_type in ("cpu", "gpu", "dcu")
  276. def __call__(self, x: Sequence[np.ndarray]) -> List[np.ndarray]:
  277. names = self.predictor.get_input_names()
  278. if len(names) != len(x):
  279. raise ValueError(
  280. f"The number of inputs does not match the model: {len(names)} vs {len(x)}"
  281. )
  282. # TODO:
  283. # Ensure that input tensors follow the model's input sequence without sorting.
  284. x = _sort_inputs(x, names)
  285. x = list(map(np.ascontiguousarray, x))
  286. pred = self.infer(x)
  287. return pred
  288. def _create(
  289. self,
  290. ):
  291. """_create"""
  292. model_paths = get_model_paths(self.model_dir, self.model_file_prefix)
  293. if "paddle" not in model_paths:
  294. raise RuntimeError("No valid Paddle model found")
  295. model_file, params_file = model_paths["paddle"]
  296. if (
  297. self._option.model_name == "LaTeX_OCR_rec"
  298. and self._option.device_type == "cpu"
  299. ):
  300. import cpuinfo
  301. if (
  302. "GenuineIntel" in cpuinfo.get_cpu_info().get("vendor_id_raw", "")
  303. and self._option.run_mode != "mkldnn"
  304. ):
  305. logging.warning(
  306. "Now, the `LaTeX_OCR_rec` model only support `mkldnn` mode when running on Intel CPU devices. So using `mkldnn` instead."
  307. )
  308. self._option.run_mode = "mkldnn"
  309. logging.debug("`run_mode` updated to 'mkldnn'")
  310. if self._option.device_type == "cpu" and self._option.device_id is not None:
  311. self._option.device_id = None
  312. logging.debug("`device_id` has been set to None")
  313. if (
  314. self._option.device_type in ("gpu", "dcu")
  315. and self._option.device_id is None
  316. ):
  317. self._option.device_id = 0
  318. logging.debug("`device_id` has been set to 0")
  319. # for TRT
  320. if self._option.run_mode.startswith("trt"):
  321. assert self._option.device_type == "gpu"
  322. cache_dir = self.model_dir / CACHE_DIR / "paddle"
  323. config = self._configure_trt(
  324. model_file,
  325. params_file,
  326. cache_dir,
  327. )
  328. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  329. config.enable_use_gpu(100, self._option.device_id)
  330. # for Native Paddle and MKLDNN
  331. else:
  332. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  333. if self._option.device_type == "gpu":
  334. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  335. from lazy_paddle.inference import PrecisionType
  336. precision = (
  337. PrecisionType.Half
  338. if self._option.run_mode == "paddle_fp16"
  339. else PrecisionType.Float32
  340. )
  341. config.enable_use_gpu(100, self._option.device_id, precision)
  342. if hasattr(config, "enable_new_ir"):
  343. config.enable_new_ir(self._option.enable_new_ir)
  344. if hasattr(config, "enable_new_executor"):
  345. config.enable_new_executor()
  346. config.set_optimization_level(3)
  347. elif self._option.device_type == "npu":
  348. config.enable_custom_device("npu")
  349. if hasattr(config, "enable_new_executor"):
  350. config.enable_new_executor()
  351. elif self._option.device_type == "xpu":
  352. if hasattr(config, "enable_new_executor"):
  353. config.enable_new_executor()
  354. elif self._option.device_type == "mlu":
  355. config.enable_custom_device("mlu")
  356. if hasattr(config, "enable_new_executor"):
  357. config.enable_new_executor()
  358. elif self._option.device_type == "gcu":
  359. from paddle_custom_device.gcu import passes as gcu_passes
  360. gcu_passes.setUp()
  361. config.enable_custom_device("gcu")
  362. if hasattr(config, "enable_new_executor"):
  363. config.enable_new_ir()
  364. config.enable_new_executor()
  365. else:
  366. pass_builder = config.pass_builder()
  367. name = "PaddleX_" + self._option.model_name
  368. gcu_passes.append_passes_for_legacy_ir(pass_builder, name)
  369. elif self._option.device_type == "dcu":
  370. config.enable_use_gpu(100, self._option.device_id)
  371. if hasattr(config, "enable_new_executor"):
  372. config.enable_new_executor()
  373. # XXX: is_compiled_with_rocm() must be True on dcu platform ?
  374. if lazy_paddle.is_compiled_with_rocm():
  375. # Delete unsupported passes in dcu
  376. config.delete_pass("conv2d_add_act_fuse_pass")
  377. config.delete_pass("conv2d_add_fuse_pass")
  378. else:
  379. assert self._option.device_type == "cpu"
  380. config.disable_gpu()
  381. if "mkldnn" in self._option.run_mode:
  382. try:
  383. config.enable_mkldnn()
  384. if "bf16" in self._option.run_mode:
  385. config.enable_mkldnn_bfloat16()
  386. except Exception as e:
  387. logging.warning(
  388. "MKL-DNN is not available. We will disable MKL-DNN."
  389. )
  390. config.set_mkldnn_cache_capacity(-1)
  391. else:
  392. if hasattr(config, "disable_mkldnn"):
  393. config.disable_mkldnn()
  394. config.set_cpu_math_library_num_threads(self._option.cpu_threads)
  395. if hasattr(config, "enable_new_ir"):
  396. config.enable_new_ir(self._option.enable_new_ir)
  397. if hasattr(config, "enable_new_executor"):
  398. config.enable_new_executor()
  399. config.set_optimization_level(3)
  400. config.enable_memory_optim()
  401. for del_p in self._option.delete_pass:
  402. config.delete_pass(del_p)
  403. # Disable paddle inference logging
  404. if not DEBUG:
  405. config.disable_glog_info()
  406. predictor = lazy_paddle.inference.create_predictor(config)
  407. return predictor
  408. def _configure_trt(self, model_file, params_file, cache_dir):
  409. # TODO: Support calibration
  410. if USE_PIR_TRT:
  411. trt_save_path = cache_dir / "trt" / self.model_file_prefix
  412. _convert_trt(
  413. self._option.trt_cfg_setting,
  414. model_file,
  415. params_file,
  416. trt_save_path,
  417. self._option.device_id,
  418. self._option.trt_dynamic_shapes,
  419. self._option.trt_dynamic_shape_input_data,
  420. )
  421. model_file = trt_save_path.with_suffix(".json")
  422. params_file = trt_save_path.with_suffix(".pdiparams")
  423. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  424. else:
  425. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  426. config.set_optim_cache_dir(str(cache_dir / "optim_cache"))
  427. for func_name in self._option.trt_cfg_setting:
  428. assert hasattr(
  429. config, func_name
  430. ), f"The `{type(config)}` don't have function `{func_name}`!"
  431. args = self._option.trt_cfg_setting[func_name]
  432. if isinstance(args, list):
  433. getattr(config, func_name)(*args)
  434. else:
  435. getattr(config, func_name)(**args)
  436. if self._option.trt_use_dynamic_shapes:
  437. if self._option.trt_collect_shape_range_info:
  438. # NOTE: We always use a shape range info file.
  439. if self._option.trt_shape_range_info_path is not None:
  440. trt_shape_range_info_path = Path(
  441. self._option.trt_shape_range_info_path
  442. )
  443. else:
  444. trt_shape_range_info_path = cache_dir / "shape_range_info.pbtxt"
  445. should_collect_shape_range_info = True
  446. if not trt_shape_range_info_path.exists():
  447. trt_shape_range_info_path.parent.mkdir(
  448. parents=True, exist_ok=True
  449. )
  450. logging.info(
  451. f"Shape range info will be collected into {trt_shape_range_info_path}"
  452. )
  453. elif self._option.trt_discard_cached_shape_range_info:
  454. trt_shape_range_info_path.unlink()
  455. logging.info(
  456. f"The shape range info file ({trt_shape_range_info_path}) has been removed, and the shape range info will be re-collected."
  457. )
  458. else:
  459. logging.info(
  460. f"A shape range info file ({trt_shape_range_info_path}) already exists. There is no need to collect the info again."
  461. )
  462. should_collect_shape_range_info = False
  463. if should_collect_shape_range_info:
  464. _collect_trt_shape_range_info(
  465. str(model_file),
  466. str(params_file),
  467. self._option.device_id,
  468. str(trt_shape_range_info_path),
  469. self._option.trt_dynamic_shapes,
  470. self._option.trt_dynamic_shape_input_data,
  471. )
  472. config.enable_tuned_tensorrt_dynamic_shape(
  473. str(trt_shape_range_info_path),
  474. self._option.trt_allow_rebuild_at_runtime,
  475. )
  476. else:
  477. if self._option.trt_dynamic_shapes is not None:
  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. else:
  490. raise RuntimeError("No dynamic shape information provided")
  491. return config