config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. import yaml
  16. from typing import Union
  17. from ...base import BaseConfig
  18. from ....utils.misc import abspath
  19. from ..config_utils import load_config, merge_config
  20. class TextRecConfig(BaseConfig):
  21. """ Text Recognition Config """
  22. def update(self, dict_like_obj: list):
  23. """update self
  24. Args:
  25. dict_like_obj (dict): dict of pairs(key0.key1.idx.key2=value).
  26. """
  27. dict_ = merge_config(self.dict, dict_like_obj)
  28. self.reset_from_dict(dict_)
  29. def load(self, config_file_path: str):
  30. """load config from yaml file
  31. Args:
  32. config_file_path (str): the path of yaml file.
  33. Raises:
  34. TypeError: the content of yaml file `config_file_path` error.
  35. """
  36. dict_ = load_config(config_file_path)
  37. if not isinstance(dict_, dict):
  38. raise TypeError
  39. self.reset_from_dict(dict_)
  40. def dump(self, config_file_path: str):
  41. """dump self to yaml file
  42. Args:
  43. config_file_path (str): the path to save self as yaml file.
  44. """
  45. with open(config_file_path, 'w', encoding='utf-8') as f:
  46. yaml.dump(self.dict, f, default_flow_style=False, sort_keys=False)
  47. def update_dataset(
  48. self,
  49. dataset_path: str,
  50. dataset_type: str=None,
  51. *,
  52. train_list_path: str=None, ):
  53. """update dataset settings
  54. Args:
  55. dataset_path (str): the root path of dataset.
  56. dataset_type (str, optional): dataset type. Defaults to None.
  57. train_list_path (str, optional): the path of train dataset annotation file . Defaults to None.
  58. Raises:
  59. ValueError: the dataset_type error.
  60. """
  61. dataset_path = abspath(dataset_path)
  62. if dataset_type is None:
  63. dataset_type = 'TextRecDataset'
  64. if train_list_path:
  65. train_list_path = f"{train_list_path}"
  66. else:
  67. train_list_path = os.path.join(dataset_path, 'train.txt')
  68. if dataset_type == 'TextRecDataset' or "MSTextRecDataset":
  69. _cfg = {
  70. 'Train.dataset.name': dataset_type,
  71. 'Train.dataset.data_dir': dataset_path,
  72. 'Train.dataset.label_file_list': [train_list_path],
  73. 'Eval.dataset.name': 'TextRecDataset',
  74. 'Eval.dataset.data_dir': dataset_path,
  75. 'Eval.dataset.label_file_list':
  76. [os.path.join(dataset_path, 'val.txt')],
  77. 'Global.character_dict_path':
  78. os.path.join(dataset_path, 'dict.txt')
  79. }
  80. self.update(_cfg)
  81. else:
  82. raise ValueError(f"{repr(dataset_type)} is not supported.")
  83. def update_batch_size(self, batch_size: int, mode: str='train'):
  84. """update batch size setting
  85. Args:
  86. batch_size (int): the batch size number to set.
  87. mode (str, optional): the mode that to be set batch size, must be one of 'train', 'eval', 'test'.
  88. Defaults to 'train'.
  89. Raises:
  90. ValueError: mode error.
  91. """
  92. _cfg = {
  93. 'Train.loader.batch_size_per_card': batch_size,
  94. 'Eval.loader.batch_size_per_card': batch_size,
  95. }
  96. if "sampler" in self.dict['Train']:
  97. _cfg['Train.sampler.first_bs'] = batch_size
  98. self.update(_cfg)
  99. def update_learning_rate(self, learning_rate: float):
  100. """update learning rate
  101. Args:
  102. learning_rate (float): the learning rate value to set.
  103. """
  104. _cfg = {'Optimizer.lr.learning_rate': learning_rate, }
  105. self.update(_cfg)
  106. def update_label_dict_path(self, dict_path: str):
  107. """update label dict file path
  108. Args:
  109. dict_path (str): the path to label dict file.
  110. """
  111. _cfg = {'Global.character_dict_path': abspath(dict_path), }
  112. self.update(_cfg)
  113. def update_warmup_epochs(self, warmup_epochs: int):
  114. """update warmup epochs
  115. Args:
  116. warmup_epochs (int): the warmup epochs value to set.
  117. """
  118. _cfg = {'Optimizer.lr.warmup_epoch': warmup_epochs}
  119. self.update(_cfg)
  120. def update_pretrained_weights(self, pretrained_model: str):
  121. """update pretrained weight path
  122. Args:
  123. pretrained_model (str): the local path or url of pretrained weight file to set.
  124. """
  125. if pretrained_model:
  126. if not pretrained_model.startswith(
  127. 'http://') and not pretrained_model.startswith('https://'):
  128. pretrained_model = abspath(pretrained_model)
  129. self.update({
  130. 'Global.pretrained_model': pretrained_model,
  131. 'Global.checkpoints': ''
  132. })
  133. # TODO
  134. def update_class_path(self, class_path: str):
  135. """_summary_
  136. Args:
  137. class_path (str): _description_
  138. """
  139. self.update({'PostProcess.class_path': class_path, })
  140. def _update_amp(self, amp: Union[None, str]):
  141. """update AMP settings
  142. Args:
  143. amp (None | str): the AMP level if it is not None or `OFF`.
  144. """
  145. _cfg = {
  146. 'Global.use_amp': amp is not None and amp != 'OFF',
  147. 'Global.amp_level': amp,
  148. }
  149. self.update(_cfg)
  150. def update_device(self, device: str):
  151. """update device setting
  152. Args:
  153. device (str): the running device to set
  154. """
  155. device = device.split(':')[0]
  156. default_cfg = {
  157. 'Global.use_gpu': False,
  158. 'Global.use_xpu': False,
  159. 'Global.use_npu': False,
  160. 'Global.use_mlu': False,
  161. }
  162. device_cfg = {
  163. 'cpu': {},
  164. 'gpu': {
  165. 'Global.use_gpu': True
  166. },
  167. 'xpu': {
  168. 'Global.use_xpu': True
  169. },
  170. 'mlu': {
  171. 'Global.use_mlu': True
  172. },
  173. 'npu': {
  174. 'Global.use_npu': True
  175. }
  176. }
  177. default_cfg.update(device_cfg[device])
  178. self.update(default_cfg)
  179. def _update_epochs(self, epochs: int):
  180. """update epochs setting
  181. Args:
  182. epochs (int): the epochs number value to set
  183. """
  184. self.update({'Global.epoch_num': epochs})
  185. def _update_checkpoints(self, resume_path: Union[None, str]):
  186. """update checkpoint setting
  187. Args:
  188. resume_path (None | str): the resume training setting. if is `None`, train from scratch, otherwise,
  189. train from checkpoint file that path is `.pdparams` file.
  190. """
  191. self.update({
  192. 'Global.checkpoints': abspath(resume_path),
  193. 'Global.pretrained_model': ''
  194. })
  195. def _update_to_static(self, dy2st: bool):
  196. """update config to set dynamic to static mode
  197. Args:
  198. dy2st (bool): whether or not to use the dynamic to static mode.
  199. """
  200. self.update({'Global.to_static': dy2st})
  201. def _update_use_vdl(self, use_vdl: bool):
  202. """update config to set VisualDL
  203. Args:
  204. use_vdl (bool): whether or not to use VisualDL.
  205. """
  206. self.update({'Global.use_visualdl': use_vdl})
  207. def _update_output_dir(self, save_dir: str):
  208. """update output directory
  209. Args:
  210. save_dir (str): the path to save output.
  211. """
  212. self.update({'Global.save_model_dir': abspath(save_dir)})
  213. # TODO
  214. # def _update_log_interval(self, log_interval):
  215. # self.update({'Global.print_batch_step': log_interval})
  216. def update_log_interval(self, log_interval: int):
  217. """update log interval(by steps)
  218. Args:
  219. log_interval (int): the log interval value to set.
  220. """
  221. self.update({'Global.print_batch_step': log_interval})
  222. # def _update_eval_interval(self, eval_start_step, eval_interval):
  223. # self.update({
  224. # 'Global.eval_batch_step': [eval_start_step, eval_interval]
  225. # })
  226. def update_log_ranks(self, device):
  227. """update log ranks
  228. Args:
  229. device (str): the running device to set
  230. """
  231. log_ranks = device.split(':')[1]
  232. self.update({'Global.log_ranks': log_ranks})
  233. def update_print_mem_info(self, print_mem_info: bool):
  234. """setting print memory info"""
  235. assert isinstance(print_mem_info,
  236. bool), "print_mem_info should be a bool"
  237. self.update({'Global.print_mem_info': f'{print_mem_info}'})
  238. def update_shared_memory(self, shared_memeory: bool):
  239. """update shared memory setting of train and eval dataloader
  240. Args:
  241. shared_memeory (bool): whether or not to use shared memory
  242. """
  243. assert isinstance(shared_memeory,
  244. bool), "shared_memeory should be a bool"
  245. _cfg = {
  246. 'Train.loader.use_shared_memory': f'{shared_memeory}',
  247. 'Train.loader.use_shared_memory': f'{shared_memeory}',
  248. }
  249. self.update(_cfg)
  250. def update_shuffle(self, shuffle: bool):
  251. """update shuffle setting of train and eval dataloader
  252. Args:
  253. shuffle (bool): whether or not to shuffle the data
  254. """
  255. assert isinstance(shuffle, bool), "shuffle should be a bool"
  256. _cfg = {
  257. f'Train.loader.shuffle': shuffle,
  258. f'Train.loader.shuffle': shuffle,
  259. }
  260. self.update(_cfg)
  261. def update_cal_metrics(self, cal_metrics: bool):
  262. """update calculate metrics setting
  263. Args:
  264. cal_metrics (bool): whether or not to calculate metrics during train
  265. """
  266. assert isinstance(cal_metrics, bool), "cal_metrics should be a bool"
  267. self.update({'Global.cal_metric_during_train': f'{cal_metrics}'})
  268. def update_seed(self, seed: int):
  269. """update seed
  270. Args:
  271. seed (int): the random seed value to set
  272. """
  273. assert isinstance(seed, int), "seed should be an int"
  274. self.update({'Global.seed': seed})
  275. def _update_eval_interval_by_epoch(self, eval_interval):
  276. """update eval interval(by epoch)
  277. Args:
  278. eval_interval (int): the eval interval value to set.
  279. """
  280. self.update({'Global.eval_batch_epoch': eval_interval})
  281. def update_eval_interval(self, eval_interval: int, eval_start_step: int=0):
  282. """update eval interval(by steps)
  283. Args:
  284. eval_interval (int): the eval interval value to set.
  285. eval_start_step (int, optional): step number from which the evaluation is enabled. Defaults to 0.
  286. """
  287. self._update_eval_interval(eval_start_step, eval_interval)
  288. def _update_save_interval(self, save_interval: int):
  289. """update save interval(by steps)
  290. Args:
  291. save_interval (int): the save interval value to set.
  292. """
  293. self.update({'Global.save_epoch_step': save_interval})
  294. def update_save_interval(self, save_interval: int):
  295. """update save interval(by steps)
  296. Args:
  297. save_interval (int): the save interval value to set.
  298. """
  299. self._update_save_interval(save_interval)
  300. def _update_infer_img(self, infer_img: str, infer_list: str=None):
  301. """update image list to be infered
  302. Args:
  303. infer_img (str): path to the image file to be infered. It would be ignored when `infer_list` is be set.
  304. infer_list (str, optional): path to the .txt file containing the paths to image to be infered.
  305. Defaults to None.
  306. """
  307. if infer_list:
  308. self.update({'Global.infer_list': infer_list})
  309. self.update({'Global.infer_img': infer_img})
  310. def _update_save_inference_dir(self, save_inference_dir: str):
  311. """update the directory saving infer outputs
  312. Args:
  313. save_inference_dir (str): the directory saving infer outputs.
  314. """
  315. self.update({'Global.save_inference_dir': abspath(save_inference_dir)})
  316. def _update_save_res_path(self, save_res_path: str):
  317. """update the .txt file path saving OCR model inference result
  318. Args:
  319. save_res_path (str): the .txt file path saving OCR model inference result.
  320. """
  321. self.update({'Global.save_res_path': abspath(save_res_path)})
  322. def update_num_workers(self,
  323. num_workers: int,
  324. modes: Union[str, list]=['train', 'eval']):
  325. """update workers number of train or eval dataloader
  326. Args:
  327. num_workers (int): the value of train and eval dataloader workers number to set.
  328. modes (str | [list], optional): mode. Defaults to ['train', 'eval'].
  329. Raises:
  330. ValueError: mode error. The `mode` should be `train`, `eval` or `['train', 'eval']`.
  331. """
  332. if not isinstance(modes, list):
  333. modes = [modes]
  334. for mode in modes:
  335. if not mode in ('train', 'eval'):
  336. raise ValueError
  337. if mode == 'train':
  338. self['Train']['loader']['num_workers'] = num_workers
  339. else:
  340. self['Eval']['loader']['num_workers'] = num_workers
  341. def _get_model_type(self) -> str:
  342. """get model type
  343. Returns:
  344. str: model type, i.e. `Architecture.algorithm` or `Architecture.Models.Student.algorithm`.
  345. """
  346. if 'Models' in self.dict['Architecture']:
  347. return self.dict['Architecture']['Models']['Student']['algorithm']
  348. return self.dict['Architecture']['algorithm']
  349. def get_epochs_iters(self) -> int:
  350. """get epochs
  351. Returns:
  352. int: the epochs value, i.e., `Global.epochs` in config.
  353. """
  354. return self.dict['Global']['epoch_num']
  355. def get_learning_rate(self) -> float:
  356. """get learning rate
  357. Returns:
  358. float: the learning rate value, i.e., `Optimizer.lr.learning_rate` in config.
  359. """
  360. return self.dict['Optimizer']['lr']['learning_rate']
  361. def get_batch_size(self, mode='train') -> int:
  362. """get batch size
  363. Args:
  364. mode (str, optional): the mode that to be get batch size value, must be one of 'train', 'eval', 'test'.
  365. Defaults to 'train'.
  366. Returns:
  367. int: the batch size value of `mode`, i.e., `DataLoader.{mode}.sampler.batch_size` in config.
  368. """
  369. return self.dict['Train']['loader']['batch_size_per_card']
  370. def get_qat_epochs_iters(self) -> int:
  371. """get qat epochs
  372. Returns:
  373. int: the epochs value.
  374. """
  375. return self.get_epochs_iters()
  376. def get_qat_learning_rate(self) -> float:
  377. """get qat learning rate
  378. Returns:
  379. float: the learning rate value.
  380. """
  381. return self.get_learning_rate()
  382. def get_label_dict_path(self) -> str:
  383. """get label dict file path
  384. Returns:
  385. str: the label dict file path, i.e., `Global.character_dict_path` in config.
  386. """
  387. return self.dict['Global']['character_dict_path']
  388. def _get_dataset_root(self) -> str:
  389. """get root directory of dataset, i.e. `DataLoader.Train.dataset.data_dir`
  390. Returns:
  391. str: the root directory of dataset
  392. """
  393. return self.dict['Train']['dataset']['data_dir']
  394. def _get_infer_shape(self) -> str:
  395. """get resize scale of ResizeImg operation in the evaluation
  396. Returns:
  397. str: resize scale, i.e. `Eval.dataset.transforms.ResizeImg.image_shape`
  398. """
  399. size = None
  400. transforms = self.dict['Eval']['dataset']['transforms']
  401. for op in transforms:
  402. op_name = list(op)[0]
  403. if 'ResizeImg' in op_name:
  404. size = op[op_name]['image_shape']
  405. return ','.join([str(x) for x in size])
  406. def get_train_save_dir(self) -> str:
  407. """get the directory to save output
  408. Returns:
  409. str: the directory to save output
  410. """
  411. return self['Global']['save_model_dir']
  412. def get_predict_save_dir(self) -> str:
  413. """get the directory to save output in predicting
  414. Returns:
  415. str: the directory to save output
  416. """
  417. return os.path.dirname(self['Global']['save_res_path'])