config.py 19 KB

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