model.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. import os
  15. from ...base import BaseModel
  16. from ...base.utils.arg import CLIArgument
  17. from ...base.utils.subprocess import CompletedProcess
  18. from ....utils.device import parse_device
  19. from ....utils.misc import abspath
  20. from ....utils import logging
  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. config.update({"Global.uniform_output_enabled": True})
  113. config.update({"Global.pdx_model_name": self.name})
  114. hpi_config_path = self.model_info.get("hpi_config_path", None)
  115. config.update({"Global.hpi_config_path": hpi_config_path})
  116. self._assert_empty_kwargs(kwargs)
  117. with self._create_new_config_file() as config_path:
  118. config.dump(config_path)
  119. return self.runner.train(
  120. config_path, cli_args, device, ips, save_dir, do_eval=do_eval
  121. )
  122. def evaluate(
  123. self,
  124. weight_path: str,
  125. batch_size: int = None,
  126. ips: str = None,
  127. device: str = "gpu",
  128. amp: str = "OFF",
  129. num_workers: int = None,
  130. **kwargs,
  131. ) -> CompletedProcess:
  132. """evaluate self using specified weight
  133. Args:
  134. weight_path (str): the path of model weight file to be evaluated.
  135. batch_size (int, optional): the batch size value in evaluating. Defaults to None.
  136. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  137. device (str, optional): the running device. Defaults to 'gpu'.
  138. amp (str, optional): the AMP setting. Defaults to 'OFF'.
  139. num_workers (int, optional): the workers number in evaluating. Defaults to None.
  140. Returns:
  141. CompletedProcess: the result of evaluating subprocess execution.
  142. """
  143. config = self.config.copy()
  144. weight_path = abspath(weight_path)
  145. config._update_checkpoints(weight_path)
  146. if batch_size is not None:
  147. config.update_batch_size(batch_size)
  148. # No need to handle `ips`
  149. config.update_device(device)
  150. config._update_amp(amp)
  151. if num_workers is not None:
  152. config.update_num_workers(num_workers, "eval")
  153. self._assert_empty_kwargs(kwargs)
  154. with self._create_new_config_file() as config_path:
  155. config.dump(config_path)
  156. cp = self.runner.evaluate(config_path, [], device, ips)
  157. return cp
  158. def predict(
  159. self,
  160. weight_path: str,
  161. input_path: str,
  162. device: str = "gpu",
  163. save_dir: str = None,
  164. **kwargs,
  165. ) -> CompletedProcess:
  166. """predict using specified weight
  167. Args:
  168. weight_path (str): the path of model weight file used to predict.
  169. input_path (str): the path of image file to be predicted.
  170. device (str, optional): the running device. Defaults to 'gpu'.
  171. save_dir (str, optional): the directory path to save predict output. Defaults to None.
  172. Returns:
  173. CompletedProcess: the result of predicting subprocess execution.
  174. """
  175. config = self.config.copy()
  176. weight_path = abspath(weight_path)
  177. config.update_pretrained_weights(weight_path)
  178. input_path = abspath(input_path)
  179. config._update_infer_img(
  180. input_path, infer_list=kwargs.pop("input_list_path", None)
  181. )
  182. config.update_device(device)
  183. # TODO: Handle `device`
  184. logging.warning("`device` will not be used.")
  185. if save_dir is not None:
  186. save_dir = abspath(save_dir)
  187. else:
  188. save_dir = abspath(config.get_predict_save_dir())
  189. config._update_save_res_path(os.path.join(save_dir, "res.txt"))
  190. self._assert_empty_kwargs(kwargs)
  191. with self._create_new_config_file() as config_path:
  192. config.dump(config_path)
  193. return self.runner.predict(config_path, [], device)
  194. def export(self, weight_path: str, save_dir: str, **kwargs) -> CompletedProcess:
  195. """export the dynamic model to static model
  196. Args:
  197. weight_path (str): the model weight file path that used to export.
  198. save_dir (str): the directory path to save export output.
  199. Returns:
  200. CompletedProcess: the result of exporting subprocess execution.
  201. """
  202. config = self.config.copy()
  203. if not weight_path.startswith("http"):
  204. weight_path = abspath(weight_path)
  205. config.update_pretrained_weights(weight_path)
  206. save_dir = abspath(save_dir)
  207. config._update_save_inference_dir(save_dir)
  208. class_path = kwargs.pop("class_path", None)
  209. if class_path is not None:
  210. config.update_class_path(class_path)
  211. # PDX related settings
  212. config.update({"Global.pdx_model_name": self.name})
  213. hpi_config_path = self.model_info.get("hpi_config_path", None)
  214. config.update({"Global.hpi_config_path": hpi_config_path})
  215. self._assert_empty_kwargs(kwargs)
  216. with self._create_new_config_file() as config_path:
  217. config.dump(config_path)
  218. return self.runner.export(config_path, [], None, save_dir)
  219. def infer(
  220. self,
  221. model_dir: str,
  222. input_path: str,
  223. device: str = "gpu",
  224. save_dir: str = None,
  225. **kwargs,
  226. ) -> CompletedProcess:
  227. """predict image using infernece model
  228. Args:
  229. model_dir (str): the directory path of inference model files that would use to predict.
  230. input_path (str): the path of image that would be predict.
  231. device (str, optional): the running device. Defaults to 'gpu'.
  232. save_dir (str, optional): the directory path to save output. Defaults to None.
  233. Returns:
  234. CompletedProcess: the result of infering subprocess execution.
  235. """
  236. config = self.config.copy()
  237. cli_args = []
  238. model_dir = abspath(model_dir)
  239. cli_args.append(CLIArgument("--rec_model_dir", model_dir))
  240. input_path = abspath(input_path)
  241. cli_args.append(CLIArgument("--image_dir", input_path))
  242. device_type, _ = parse_device(device)
  243. cli_args.append(CLIArgument("--use_gpu", str(device_type == "gpu")))
  244. if save_dir is not None:
  245. logging.warning("`save_dir` will not be used.")
  246. dict_path = kwargs.pop("dict_path", None)
  247. if dict_path is not None:
  248. dict_path = abspath(dict_path)
  249. else:
  250. dict_path = config.get_label_dict_path()
  251. cli_args.append(CLIArgument("--rec_char_dict_path", dict_path))
  252. model_type = config._get_model_type()
  253. cli_args.append(CLIArgument("--rec_algorithm", model_type))
  254. infer_shape = config._get_infer_shape()
  255. if infer_shape is not None:
  256. cli_args.append(CLIArgument("--rec_image_shape", infer_shape))
  257. self._assert_empty_kwargs(kwargs)
  258. with self._create_new_config_file() as config_path:
  259. config.dump(config_path)
  260. return self.runner.infer(config_path, cli_args, device)
  261. def compression(
  262. self,
  263. weight_path: str,
  264. batch_size: int = None,
  265. learning_rate: float = None,
  266. epochs_iters: int = None,
  267. device: str = "gpu",
  268. use_vdl: bool = True,
  269. save_dir: str = None,
  270. **kwargs,
  271. ) -> CompletedProcess:
  272. """compression model
  273. Args:
  274. weight_path (str): the path to weight file of model.
  275. batch_size (int, optional): the batch size value of compression training. Defaults to None.
  276. learning_rate (float, optional): the learning rate value of compression training. Defaults to None.
  277. epochs_iters (int, optional): the epochs or iters of compression training. Defaults to None.
  278. device (str, optional): the device to run compression training. Defaults to 'gpu'.
  279. use_vdl (bool, optional): whether or not to use VisualDL. Defaults to True.
  280. save_dir (str, optional): the directory to save output. Defaults to None.
  281. Returns:
  282. CompletedProcess: the result of compression subprocess execution.
  283. """
  284. config = self.config.copy()
  285. export_cli_args = []
  286. weight_path = abspath(weight_path)
  287. config.update_pretrained_weights(weight_path)
  288. if batch_size is not None:
  289. config.update_batch_size(batch_size)
  290. if learning_rate is not None:
  291. config.update_learning_rate(learning_rate)
  292. if epochs_iters is not None:
  293. config._update_epochs(epochs_iters)
  294. config.update_device(device)
  295. config._update_use_vdl(use_vdl)
  296. if save_dir is not None:
  297. save_dir = abspath(save_dir)
  298. else:
  299. save_dir = abspath(config.get_train_save_dir())
  300. config._update_output_dir(save_dir)
  301. export_cli_args.append(
  302. CLIArgument(
  303. "-o", f"Global.save_inference_dir={os.path.join(save_dir, 'export')}"
  304. )
  305. )
  306. self._assert_empty_kwargs(kwargs)
  307. with self._create_new_config_file() as config_path:
  308. config.dump(config_path)
  309. return self.runner.compression(
  310. config_path, [], export_cli_args, device, save_dir
  311. )