config.py 18 KB

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