model.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 os
  15. from ....utils import logging
  16. from ....utils.device import parse_device
  17. from ....utils.misc import abspath
  18. from ...base import BaseModel
  19. from ...base.utils.arg import CLIArgument
  20. from ...base.utils.subprocess import CompletedProcess
  21. class TextRecModel(BaseModel):
  22. """Text Recognition Model"""
  23. METRICS = [
  24. "acc",
  25. "norm_edit_dis",
  26. "Teacher_acc",
  27. "Teacher_norm_edit_dis",
  28. "precision",
  29. "recall",
  30. "hmean",
  31. ]
  32. def train(
  33. self,
  34. batch_size: int = None,
  35. learning_rate: float = None,
  36. epochs_iters: int = None,
  37. ips: str = None,
  38. device: str = "gpu",
  39. resume_path: str = None,
  40. dy2st: bool = False,
  41. amp: str = "OFF",
  42. num_workers: int = None,
  43. use_vdl: bool = True,
  44. save_dir: str = None,
  45. **kwargs,
  46. ) -> CompletedProcess:
  47. """train self
  48. Args:
  49. batch_size (int, optional): the train batch size value. Defaults to None.
  50. learning_rate (float, optional): the train learning rate value. Defaults to None.
  51. epochs_iters (int, optional): the train epochs value. Defaults to None.
  52. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  53. device (str, optional): the running device. Defaults to 'gpu'.
  54. resume_path (str, optional): the checkpoint file path to resume training. Train from scratch if it is set
  55. to None. Defaults to None.
  56. dy2st (bool, optional): Enable dynamic to static. Defaults to False.
  57. amp (str, optional): the amp settings. Defaults to 'OFF'.
  58. num_workers (int, optional): the workers number. Defaults to None.
  59. use_vdl (bool, optional): enable VisualDL. Defaults to True.
  60. save_dir (str, optional): the directory path to save train output. Defaults to None.
  61. Returns:
  62. CompletedProcess: the result of training subprocess execution.
  63. """
  64. config = self.config.copy()
  65. if batch_size is not None:
  66. config.update_batch_size(batch_size)
  67. if learning_rate is not None:
  68. config.update_learning_rate(learning_rate)
  69. if epochs_iters is not None:
  70. config._update_epochs(epochs_iters)
  71. # No need to handle `ips`
  72. config.update_device(device)
  73. if resume_path is not None:
  74. resume_path = abspath(resume_path)
  75. config._update_checkpoints(resume_path)
  76. config._update_to_static(dy2st)
  77. config._update_amp(amp)
  78. if num_workers is not None:
  79. config.update_num_workers(num_workers, "train")
  80. config._update_use_vdl(use_vdl)
  81. if save_dir is not None:
  82. save_dir = abspath(save_dir)
  83. else:
  84. save_dir = abspath(config.get_train_save_dir())
  85. config._update_output_dir(save_dir)
  86. cli_args = []
  87. do_eval = kwargs.pop("do_eval", True)
  88. profile = kwargs.pop("profile", None)
  89. if profile is not None:
  90. cli_args.append(CLIArgument("--profiler_options", profile))
  91. # Benchmarking mode settings
  92. benchmark = kwargs.pop("benchmark", None)
  93. if benchmark is not None:
  94. envs = benchmark.get("env", None)
  95. seed = benchmark.get("seed", None)
  96. do_eval = benchmark.get("do_eval", False)
  97. num_workers = benchmark.get("num_workers", None)
  98. config.update_log_ranks(device)
  99. config._update_amp(benchmark.get("amp", None))
  100. config.update_shuffle(benchmark.get("shuffle", False))
  101. config.update_cal_metrics(benchmark.get("cal_metrics", True))
  102. config.update_shared_memory(benchmark.get("shared_memory", True))
  103. config.update_print_mem_info(benchmark.get("print_mem_info", True))
  104. if num_workers is not None:
  105. config.update_num_workers(num_workers)
  106. if seed is not None:
  107. config.update_seed(seed)
  108. if envs is not None:
  109. for env_name, env_value in envs.items():
  110. os.environ[env_name] = str(env_value)
  111. # PDX related settings
  112. device_type = device.split(":")[0]
  113. uniform_output_enabled = kwargs.pop("uniform_output_enabled", True)
  114. config.update({"Global.uniform_output_enabled": uniform_output_enabled})
  115. config.update({"Global.model_name": self.name})
  116. config.update({"Global.export_with_pir": kwargs.pop("export_with_pir", False)})
  117. self._assert_empty_kwargs(kwargs)
  118. with self._create_new_config_file() as config_path:
  119. config.dump(config_path)
  120. return self.runner.train(
  121. config_path, cli_args, device, ips, save_dir, do_eval=do_eval
  122. )
  123. def evaluate(
  124. self,
  125. weight_path: str,
  126. batch_size: int = None,
  127. ips: str = None,
  128. device: str = "gpu",
  129. amp: str = "OFF",
  130. num_workers: int = None,
  131. **kwargs,
  132. ) -> CompletedProcess:
  133. """evaluate self using specified weight
  134. Args:
  135. weight_path (str): the path of model weight file to be evaluated.
  136. batch_size (int, optional): the batch size value in evaluating. Defaults to None.
  137. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  138. device (str, optional): the running device. Defaults to 'gpu'.
  139. amp (str, optional): the AMP setting. Defaults to 'OFF'.
  140. num_workers (int, optional): the workers number in evaluating. Defaults to None.
  141. Returns:
  142. CompletedProcess: the result of evaluating subprocess execution.
  143. """
  144. config = self.config.copy()
  145. weight_path = abspath(weight_path)
  146. config._update_checkpoints(weight_path)
  147. if batch_size is not None:
  148. config.update_batch_size(batch_size)
  149. # No need to handle `ips`
  150. config.update_device(device)
  151. config._update_amp(amp)
  152. if num_workers is not None:
  153. config.update_num_workers(num_workers, "eval")
  154. self._assert_empty_kwargs(kwargs)
  155. with self._create_new_config_file() as config_path:
  156. config.dump(config_path)
  157. cp = self.runner.evaluate(config_path, [], device, ips)
  158. return cp
  159. def predict(
  160. self,
  161. weight_path: str,
  162. input_path: str,
  163. device: str = "gpu",
  164. save_dir: str = None,
  165. **kwargs,
  166. ) -> CompletedProcess:
  167. """predict using specified weight
  168. Args:
  169. weight_path (str): the path of model weight file used to predict.
  170. input_path (str): the path of image file to be predicted.
  171. device (str, optional): the running device. Defaults to 'gpu'.
  172. save_dir (str, optional): the directory path to save predict output. Defaults to None.
  173. Returns:
  174. CompletedProcess: the result of predicting subprocess execution.
  175. """
  176. config = self.config.copy()
  177. weight_path = abspath(weight_path)
  178. config.update_pretrained_weights(weight_path)
  179. input_path = abspath(input_path)
  180. config._update_infer_img(
  181. input_path, infer_list=kwargs.pop("input_list_path", None)
  182. )
  183. config.update_device(device)
  184. # TODO: Handle `device`
  185. logging.warning("`device` will not be used.")
  186. if save_dir is not None:
  187. save_dir = abspath(save_dir)
  188. else:
  189. save_dir = abspath(config.get_predict_save_dir())
  190. config._update_save_res_path(os.path.join(save_dir, "res.txt"))
  191. self._assert_empty_kwargs(kwargs)
  192. with self._create_new_config_file() as config_path:
  193. config.dump(config_path)
  194. return self.runner.predict(config_path, [], device)
  195. def export(self, weight_path: str, save_dir: str, **kwargs) -> CompletedProcess:
  196. """export the dynamic model to static model
  197. Args:
  198. weight_path (str): the model weight file path that used to export.
  199. save_dir (str): the directory path to save export output.
  200. Returns:
  201. CompletedProcess: the result of exporting subprocess execution.
  202. """
  203. config = self.config.copy()
  204. device = kwargs.pop("device", None)
  205. if device:
  206. config.update_device(device)
  207. if not weight_path.startswith("http"):
  208. weight_path = abspath(weight_path)
  209. config.update_pretrained_weights(weight_path)
  210. save_dir = abspath(save_dir)
  211. config._update_save_inference_dir(save_dir)
  212. class_path = kwargs.pop("class_path", None)
  213. if class_path is not None:
  214. config.update_class_path(class_path)
  215. # PDX related settings
  216. uniform_output_enabled = kwargs.pop("uniform_output_enabled", True)
  217. config.update({"Global.uniform_output_enabled": uniform_output_enabled})
  218. config.update({"Global.model_name": self.name})
  219. config.update({"Global.export_with_pir": kwargs.pop("export_with_pir", False)})
  220. self._assert_empty_kwargs(kwargs)
  221. with self._create_new_config_file() as config_path:
  222. config.dump(config_path)
  223. return self.runner.export(config_path, [], None, save_dir)
  224. def infer(
  225. self,
  226. model_dir: str,
  227. input_path: str,
  228. device: str = "gpu",
  229. save_dir: str = None,
  230. **kwargs,
  231. ) -> CompletedProcess:
  232. """predict image using infernece model
  233. Args:
  234. model_dir (str): the directory path of inference model files that would use to predict.
  235. input_path (str): the path of image that would be predict.
  236. device (str, optional): the running device. Defaults to 'gpu'.
  237. save_dir (str, optional): the directory path to save output. Defaults to None.
  238. Returns:
  239. CompletedProcess: the result of inferring subprocess execution.
  240. """
  241. config = self.config.copy()
  242. cli_args = []
  243. model_dir = abspath(model_dir)
  244. cli_args.append(CLIArgument("--rec_model_dir", model_dir))
  245. input_path = abspath(input_path)
  246. cli_args.append(CLIArgument("--image_dir", input_path))
  247. device_type, _ = parse_device(device)
  248. cli_args.append(CLIArgument("--use_gpu", str(device_type == "gpu")))
  249. if save_dir is not None:
  250. logging.warning("`save_dir` will not be used.")
  251. dict_path = kwargs.pop("dict_path", None)
  252. if dict_path is not None:
  253. dict_path = abspath(dict_path)
  254. else:
  255. dict_path = config.get_label_dict_path()
  256. cli_args.append(CLIArgument("--rec_char_dict_path", dict_path))
  257. model_type = config._get_model_type()
  258. cli_args.append(CLIArgument("--rec_algorithm", model_type))
  259. infer_shape = config._get_infer_shape()
  260. if infer_shape is not None:
  261. cli_args.append(CLIArgument("--rec_image_shape", infer_shape))
  262. self._assert_empty_kwargs(kwargs)
  263. with self._create_new_config_file() as config_path:
  264. config.dump(config_path)
  265. return self.runner.infer(config_path, cli_args, device)
  266. def compression(
  267. self,
  268. weight_path: str,
  269. batch_size: int = None,
  270. learning_rate: float = None,
  271. epochs_iters: int = None,
  272. device: str = "gpu",
  273. use_vdl: bool = True,
  274. save_dir: str = None,
  275. **kwargs,
  276. ) -> CompletedProcess:
  277. """compression model
  278. Args:
  279. weight_path (str): the path to weight file of model.
  280. batch_size (int, optional): the batch size value of compression training. Defaults to None.
  281. learning_rate (float, optional): the learning rate value of compression training. Defaults to None.
  282. epochs_iters (int, optional): the epochs or iters of compression training. Defaults to None.
  283. device (str, optional): the device to run compression training. Defaults to 'gpu'.
  284. use_vdl (bool, optional): whether or not to use VisualDL. Defaults to True.
  285. save_dir (str, optional): the directory to save output. Defaults to None.
  286. Returns:
  287. CompletedProcess: the result of compression subprocess execution.
  288. """
  289. config = self.config.copy()
  290. export_cli_args = []
  291. weight_path = abspath(weight_path)
  292. config.update_pretrained_weights(weight_path)
  293. if batch_size is not None:
  294. config.update_batch_size(batch_size)
  295. if learning_rate is not None:
  296. config.update_learning_rate(learning_rate)
  297. if epochs_iters is not None:
  298. config._update_epochs(epochs_iters)
  299. config.update_device(device)
  300. config._update_use_vdl(use_vdl)
  301. if save_dir is not None:
  302. save_dir = abspath(save_dir)
  303. else:
  304. save_dir = abspath(config.get_train_save_dir())
  305. config._update_output_dir(save_dir)
  306. export_cli_args.append(
  307. CLIArgument(
  308. "-o", f"Global.save_inference_dir={os.path.join(save_dir, 'export')}"
  309. )
  310. )
  311. self._assert_empty_kwargs(kwargs)
  312. with self._create_new_config_file() as config_path:
  313. config.dump(config_path)
  314. return self.runner.compression(
  315. config_path, [], export_cli_args, device, save_dir
  316. )