config.py 18 KB

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