model.py 13 KB

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