static_infer.py 21 KB

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