static_infer.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. model_name,
  124. mode,
  125. pp_model_file,
  126. pp_params_file,
  127. trt_save_path,
  128. dynamic_shapes,
  129. dynamic_shape_input_data,
  130. ):
  131. from lazy_paddle.tensorrt.export import (
  132. Input,
  133. TensorRTConfig,
  134. convert,
  135. PrecisionMode,
  136. )
  137. def _set_trt_config():
  138. if settings := TRT_CFG.get(model_name):
  139. for attr_name in settings:
  140. if not hasattr(trt_config, attr_name):
  141. logging.warning(f"The TensorRTConfig don't have the `{attr_name}`!")
  142. setattr(trt_config, attr_name, settings[attr_name])
  143. def _get_predictor(model_file, params_file):
  144. # HACK
  145. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  146. # NOTE: Disable oneDNN to circumvent a bug in Paddle Inference
  147. config.disable_mkldnn()
  148. config.disable_glog_info()
  149. return lazy_paddle.inference.create_predictor(config)
  150. dynamic_shape_input_data = dynamic_shape_input_data or {}
  151. predictor = _get_predictor(pp_model_file, pp_params_file)
  152. input_names = predictor.get_input_names()
  153. for name in dynamic_shapes:
  154. if name not in input_names:
  155. raise ValueError(
  156. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  157. )
  158. for name in input_names:
  159. if name not in dynamic_shapes:
  160. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  161. for name in dynamic_shape_input_data:
  162. if name not in input_names:
  163. raise ValueError(
  164. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  165. )
  166. precision_map = {
  167. "trt_int8": PrecisionMode.INT8,
  168. "trt_fp32": PrecisionMode.FP32,
  169. "trt_fp16": PrecisionMode.FP16,
  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.precision_mode = precision_map[mode]
  199. trt_config.save_model_dir = str(trt_save_path)
  200. pp_model_path = str(pp_model_file.with_suffix(""))
  201. convert(pp_model_path, trt_config)
  202. def _sort_inputs(inputs, names):
  203. # NOTE: Adjust input tensors to match the sorted sequence.
  204. indices = sorted(range(len(names)), key=names.__getitem__)
  205. inputs = [inputs[indices.index(i)] for i in range(len(inputs))]
  206. return inputs
  207. def _concatenate(*callables):
  208. def _chain(x):
  209. for c in callables:
  210. x = c(x)
  211. return x
  212. return _chain
  213. @benchmark.timeit
  214. class PaddleCopyToDevice:
  215. def __init__(self, device_type, device_id):
  216. self.device_type = device_type
  217. self.device_id = device_id
  218. def __call__(self, arrs):
  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 = [lazy_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(object):
  258. def __init__(
  259. self,
  260. model_dir: str,
  261. model_prefix: str,
  262. option: PaddlePredictorOption,
  263. ) -> None:
  264. super().__init__()
  265. self.model_dir = model_dir
  266. self.model_file_prefix = model_prefix
  267. self._option = option
  268. self.predictor = self._create()
  269. if self._use_new_inference_api:
  270. device_type = self._option.device_type
  271. device_type = "gpu" if device_type == "dcu" else device_type
  272. copy_to_device = PaddleCopyToDevice(device_type, self._option.device_id)
  273. copy_to_host = PaddleCopyToHost()
  274. model_infer = PaddleModelInfer(self.predictor)
  275. self.infer = _concatenate(copy_to_device, model_infer, copy_to_host)
  276. else:
  277. self.infer = PaddleInferChainLegacy(self.predictor)
  278. @property
  279. def _use_new_inference_api(self):
  280. # HACK: Temp fallback to legacy API via env var
  281. return INFER_BENCHMARK_USE_NEW_INFER_API
  282. # return self._option.device_type in ("cpu", "gpu", "dcu")
  283. def __call__(self, x: Sequence[np.ndarray]) -> List[np.ndarray]:
  284. names = self.predictor.get_input_names()
  285. if len(names) != len(x):
  286. raise ValueError(
  287. f"The number of inputs does not match the model: {len(names)} vs {len(x)}"
  288. )
  289. # TODO:
  290. # Ensure that input tensors follow the model's input sequence without sorting.
  291. x = _sort_inputs(x, names)
  292. x = list(map(np.ascontiguousarray, x))
  293. pred = self.infer(x)
  294. return pred
  295. def _create(
  296. self,
  297. ):
  298. """_create"""
  299. model_paths = get_model_paths(self.model_dir, self.model_file_prefix)
  300. if "paddle" not in model_paths:
  301. raise RuntimeError("No valid Paddle model found")
  302. model_file, params_file = model_paths["paddle"]
  303. if (
  304. self._option.model_name == "LaTeX_OCR_rec"
  305. and self._option.device_type == "cpu"
  306. ):
  307. import cpuinfo
  308. if (
  309. "GenuineIntel" in cpuinfo.get_cpu_info().get("vendor_id_raw", "")
  310. and self._option.run_mode != "mkldnn"
  311. ):
  312. logging.warning(
  313. "Now, the `LaTeX_OCR_rec` model only support `mkldnn` mode when running on Intel CPU devices. So using `mkldnn` instead."
  314. )
  315. self._option.run_mode = "mkldnn"
  316. logging.debug("`run_mode` updated to 'mkldnn'")
  317. if self._option.device_type == "cpu" and self._option.device_id is not None:
  318. self._option.device_id = None
  319. logging.debug("`device_id` has been set to None")
  320. if (
  321. self._option.device_type in ("gpu", "dcu")
  322. and self._option.device_id is None
  323. ):
  324. self._option.device_id = 0
  325. logging.debug("`device_id` has been set to 0")
  326. # for TRT
  327. if self._option.run_mode.startswith("trt"):
  328. assert self._option.device_type == "gpu"
  329. cache_dir = self.model_dir / CACHE_DIR / "paddle"
  330. config = self._configure_trt(
  331. model_file,
  332. params_file,
  333. cache_dir,
  334. )
  335. else:
  336. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  337. if self._option.device_type == "gpu":
  338. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  339. config.enable_use_gpu(100, self._option.device_id)
  340. if not self._option.run_mode.startswith("trt"):
  341. if hasattr(config, "enable_new_ir"):
  342. config.enable_new_ir(self._option.enable_new_ir)
  343. if hasattr(config, "enable_new_executor"):
  344. config.enable_new_executor()
  345. config.set_optimization_level(3)
  346. elif self._option.device_type == "npu":
  347. config.enable_custom_device("npu")
  348. if hasattr(config, "enable_new_executor"):
  349. config.enable_new_executor()
  350. elif self._option.device_type == "xpu":
  351. if hasattr(config, "enable_new_executor"):
  352. config.enable_new_executor()
  353. elif self._option.device_type == "mlu":
  354. config.enable_custom_device("mlu")
  355. if hasattr(config, "enable_new_executor"):
  356. config.enable_new_executor()
  357. elif self._option.device_type == "dcu":
  358. config.enable_use_gpu(100, self._option.device_id)
  359. if hasattr(config, "enable_new_executor"):
  360. config.enable_new_executor()
  361. # XXX: is_compiled_with_rocm() must be True on dcu platform ?
  362. if lazy_paddle.is_compiled_with_rocm():
  363. # Delete unsupported passes in dcu
  364. config.delete_pass("conv2d_add_act_fuse_pass")
  365. config.delete_pass("conv2d_add_fuse_pass")
  366. else:
  367. assert self._option.device_type == "cpu"
  368. config.disable_gpu()
  369. if "mkldnn" in self._option.run_mode:
  370. try:
  371. config.enable_mkldnn()
  372. if "bf16" in self._option.run_mode:
  373. config.enable_mkldnn_bfloat16()
  374. except Exception as e:
  375. logging.warning(
  376. "MKL-DNN is not available. We will disable MKL-DNN."
  377. )
  378. config.set_mkldnn_cache_capacity(-1)
  379. else:
  380. if hasattr(config, "disable_mkldnn"):
  381. config.disable_mkldnn()
  382. config.set_cpu_math_library_num_threads(self._option.cpu_threads)
  383. if hasattr(config, "enable_new_ir"):
  384. config.enable_new_ir(self._option.enable_new_ir)
  385. if hasattr(config, "enable_new_executor"):
  386. config.enable_new_executor()
  387. config.set_optimization_level(3)
  388. config.enable_memory_optim()
  389. for del_p in self._option.delete_pass:
  390. config.delete_pass(del_p)
  391. # Disable paddle inference logging
  392. if not DEBUG:
  393. config.disable_glog_info()
  394. predictor = lazy_paddle.inference.create_predictor(config)
  395. return predictor
  396. def _configure_trt(self, model_file, params_file, cache_dir):
  397. # TODO: Support calibration
  398. if USE_PIR_TRT:
  399. trt_save_path = cache_dir / "trt" / self.model_file_prefix
  400. _convert_trt(
  401. self._option.model_name,
  402. self._option.run_mode,
  403. model_file,
  404. params_file,
  405. trt_save_path,
  406. self._option.trt_dynamic_shapes,
  407. self._option.trt_dynamic_shape_input_data,
  408. )
  409. model_file = trt_save_path.with_suffix(".json")
  410. params_file = trt_save_path.with_suffix(".pdiparams")
  411. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  412. else:
  413. PRECISION_MAP = {
  414. "trt_int8": lazy_paddle.inference.Config.Precision.Int8,
  415. "trt_fp32": lazy_paddle.inference.Config.Precision.Float32,
  416. "trt_fp16": lazy_paddle.inference.Config.Precision.Half,
  417. }
  418. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  419. config.set_optim_cache_dir(str(cache_dir / "optim_cache"))
  420. config.enable_use_gpu(100, self._option.device_id)
  421. config.enable_tensorrt_engine(
  422. workspace_size=self._option.trt_max_workspace_size,
  423. max_batch_size=self._option.trt_max_batch_size,
  424. min_subgraph_size=self._option.trt_min_subgraph_size,
  425. precision_mode=PRECISION_MAP[self._option.run_mode],
  426. use_static=self._option.trt_use_static,
  427. use_calib_mode=self._option.trt_use_calib_mode,
  428. )
  429. if self._option.trt_use_dynamic_shapes:
  430. if self._option.trt_collect_shape_range_info:
  431. # NOTE: We always use a shape range info file.
  432. if self._option.trt_shape_range_info_path is not None:
  433. trt_shape_range_info_path = Path(
  434. self._option.trt_shape_range_info_path
  435. )
  436. else:
  437. trt_shape_range_info_path = cache_dir / "shape_range_info.pbtxt"
  438. should_collect_shape_range_info = True
  439. if not trt_shape_range_info_path.exists():
  440. trt_shape_range_info_path.parent.mkdir(
  441. parents=True, exist_ok=True
  442. )
  443. logging.info(
  444. f"Shape range info will be collected into {trt_shape_range_info_path}"
  445. )
  446. elif self._option.trt_discard_cached_shape_range_info:
  447. trt_shape_range_info_path.unlink()
  448. logging.info(
  449. f"The shape range info file ({trt_shape_range_info_path}) has been removed, and the shape range info will be re-collected."
  450. )
  451. else:
  452. logging.info(
  453. f"A shape range info file ({trt_shape_range_info_path}) already exists. There is no need to collect the info again."
  454. )
  455. should_collect_shape_range_info = False
  456. if should_collect_shape_range_info:
  457. _collect_trt_shape_range_info(
  458. str(model_file),
  459. str(params_file),
  460. self._option.device_id,
  461. str(trt_shape_range_info_path),
  462. self._option.trt_dynamic_shapes,
  463. self._option.trt_dynamic_shape_input_data,
  464. )
  465. config.enable_tuned_tensorrt_dynamic_shape(
  466. str(trt_shape_range_info_path),
  467. self._option.trt_allow_rebuild_at_runtime,
  468. )
  469. else:
  470. if self._option.trt_dynamic_shapes is not None:
  471. min_shapes, opt_shapes, max_shapes = {}, {}, {}
  472. for (
  473. key,
  474. shapes,
  475. ) in self._option.trt_dynamic_shapes.items():
  476. min_shapes[key] = shapes[0]
  477. opt_shapes[key] = shapes[1]
  478. max_shapes[key] = shapes[2]
  479. config.set_trt_dynamic_shape_info(
  480. min_shapes, max_shapes, opt_shapes
  481. )
  482. else:
  483. raise RuntimeError("No dynamic shape information provided")
  484. return config