config.py 19 KB

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