config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 yaml
  15. from typing import Union
  16. from paddleclas.ppcls.utils.config import get_config, override_config
  17. from ...base import BaseConfig
  18. from ....utils.misc import abspath
  19. class ClsConfig(BaseConfig):
  20. """Image Classification Task Config"""
  21. def update(self, list_like_obj: list):
  22. """update self
  23. Args:
  24. list_like_obj (list): list of pairs(key0.key1.idx.key2=value), such as:
  25. [
  26. 'topk=2',
  27. 'VALID.transforms.1.ResizeImage.resize_short=300'
  28. ]
  29. """
  30. dict_ = override_config(self.dict, list_like_obj)
  31. self.reset_from_dict(dict_)
  32. def load(self, config_file_path: str):
  33. """load config from yaml file
  34. Args:
  35. config_file_path (str): the path of yaml file.
  36. Raises:
  37. TypeError: the content of yaml file `config_file_path` error.
  38. """
  39. dict_ = yaml.load(open(config_file_path, 'rb'), Loader=yaml.Loader)
  40. if not isinstance(dict_, dict):
  41. raise TypeError
  42. self.reset_from_dict(dict_)
  43. def dump(self, config_file_path: str):
  44. """dump self to yaml file
  45. Args:
  46. config_file_path (str): the path to save self as yaml file.
  47. """
  48. with open(config_file_path, 'w', encoding='utf-8') as f:
  49. yaml.dump(self.dict, f, default_flow_style=False, sort_keys=False)
  50. def update_dataset(
  51. self,
  52. dataset_path: str,
  53. dataset_type: str=None,
  54. *,
  55. train_list_path: str=None, ):
  56. """update dataset settings
  57. Args:
  58. dataset_path (str): the root path of dataset.
  59. dataset_type (str, optional): dataset type. Defaults to None.
  60. train_list_path (str, optional): the path of train dataset annotation file . Defaults to None.
  61. Raises:
  62. ValueError: the dataset_type error.
  63. """
  64. dataset_path = abspath(dataset_path)
  65. if dataset_type is None:
  66. dataset_type = 'ClsDataset'
  67. if train_list_path:
  68. train_list_path = f"{train_list_path}"
  69. else:
  70. train_list_path = f"{dataset_path}/train.txt"
  71. if dataset_type in ['ClsDataset']:
  72. ds_cfg = [
  73. f'DataLoader.Train.dataset.name={dataset_type}',
  74. f'DataLoader.Train.dataset.image_root={dataset_path}',
  75. f'DataLoader.Train.dataset.cls_label_path={train_list_path}',
  76. f'DataLoader.Eval.dataset.name={dataset_type}',
  77. f'DataLoader.Eval.dataset.image_root={dataset_path}',
  78. f'DataLoader.Eval.dataset.cls_label_path={dataset_path}/val.txt',
  79. f'Infer.PostProcess.class_id_map_file={dataset_path}/label.txt'
  80. ]
  81. else:
  82. raise ValueError(f"{repr(dataset_type)} is not supported.")
  83. self.update(ds_cfg)
  84. def update_batch_size(self, batch_size: int, mode: str='train'):
  85. """update batch size setting
  86. Args:
  87. batch_size (int): the batch size number to set.
  88. mode (str, optional): the mode that to be set batch size, must be one of 'train', 'eval', 'test'.
  89. Defaults to 'train'.
  90. Raises:
  91. ValueError: `mode` error.
  92. """
  93. if mode == 'train':
  94. _cfg = [f'DataLoader.Train.sampler.batch_size={batch_size}']
  95. elif mode == 'eval':
  96. _cfg = [f'DataLoader.Eval.sampler.batch_size={batch_size}']
  97. elif mode == 'test':
  98. _cfg = [f'DataLoader.Infer.batch_size={batch_size}']
  99. else:
  100. raise ValueError("The input `mode` should be train, eval or test.")
  101. self.update(_cfg)
  102. def update_learning_rate(self, learning_rate: float):
  103. """update learning rate
  104. Args:
  105. learning_rate (float): the learning rate value to set.
  106. """
  107. _cfg = [f'Optimizer.lr.learning_rate={learning_rate}']
  108. self.update(_cfg)
  109. def update_warmup_epochs(self, warmup_epochs: int):
  110. """update warmup epochs
  111. Args:
  112. warmup_epochs (int): the warmup epochs value to set.
  113. """
  114. _cfg = [f'Optimizer.lr.warmup_epoch={warmup_epochs}']
  115. self.update(_cfg)
  116. def update_pretrained_weights(self, pretrained_model: str):
  117. """update pretrained weight path
  118. Args:
  119. pretrained_model (str): the local path or url of pretrained weight file to set.
  120. """
  121. assert isinstance(
  122. pretrained_model, (str, None)
  123. ), "The 'pretrained_model' should be a string, indicating the path to the '*.pdparams' file, or 'None', \
  124. indicating that no pretrained model to be used."
  125. if pretrained_model and not pretrained_model.startswith(
  126. ('http://', 'https://')):
  127. pretrained_model = abspath(
  128. pretrained_model.replace(".pdparams", ""))
  129. self.update([f'Global.pretrained_model={pretrained_model}'])
  130. def update_num_classes(self, num_classes: int):
  131. """update classes number
  132. Args:
  133. num_classes (int): the classes number value to set.
  134. """
  135. update_str_list = [f'Arch.class_num={num_classes}']
  136. if self._get_arch_name() == "DistillationModel":
  137. update_str_list.append(
  138. f"Arch.models.0.Teacher.class_num={num_classes}")
  139. update_str_list.append(
  140. f"Arch.models.1.Student.class_num={num_classes}")
  141. self.update(update_str_list)
  142. def _update_slim_config(self, slim_config_path: str):
  143. """update slim settings
  144. Args:
  145. slim_config_path (str): the path to slim config yaml file.
  146. """
  147. slim_config = yaml.load(
  148. open(slim_config_path, 'rb'), Loader=yaml.Loader)['Slim']
  149. self.update([f'Slim={slim_config}'])
  150. def _update_amp(self, amp: Union[None, str]):
  151. """update AMP settings
  152. Args:
  153. amp (None | str): the AMP settings.
  154. Raises:
  155. ValueError: AMP setting `amp` error, missing field `AMP`.
  156. """
  157. if amp is None or amp == 'OFF':
  158. if 'AMP' in self.dict:
  159. self._dict.pop('AMP')
  160. else:
  161. if 'AMP' not in self.dict:
  162. raise ValueError("Config must have AMP information.")
  163. _cfg = ['AMP.use_amp=True', f'AMP.level={amp}']
  164. self.update(_cfg)
  165. def update_num_workers(self, num_workers: int):
  166. """update workers number of train and eval dataloader
  167. Args:
  168. num_workers (int): the value of train and eval dataloader workers number to set.
  169. """
  170. _cfg = [
  171. f'DataLoader.Train.loader.num_workers={num_workers}',
  172. f'DataLoader.Eval.loader.num_workers={num_workers}',
  173. ]
  174. self.update(_cfg)
  175. def enable_shared_memory(self):
  176. """enable shared memory setting of train and eval dataloader
  177. """
  178. _cfg = [
  179. f'DataLoader.Train.loader.use_shared_memory=True',
  180. f'DataLoader.Eval.loader.use_shared_memory=True',
  181. ]
  182. self.update(_cfg)
  183. def disable_shared_memory(self):
  184. """disable shared memory setting of train and eval dataloader
  185. """
  186. _cfg = [
  187. f'DataLoader.Train.loader.use_shared_memory=False',
  188. f'DataLoader.Eval.loader.use_shared_memory=False',
  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. _cfg = [f'Global.device={device}']
  198. self.update(_cfg)
  199. def update_label_dict_path(self, dict_path: str):
  200. """update label dict file path
  201. Args:
  202. dict_path (str): the path of label dict file to set
  203. """
  204. _cfg = [f'PostProcess.Topk.class_id_map_file={abspath(dict_path)}', ]
  205. self.update(_cfg)
  206. def _update_to_static(self, dy2st: bool):
  207. """update config to set dynamic to static mode
  208. Args:
  209. dy2st (bool): whether or not to use the dynamic to static mode.
  210. """
  211. self.update([f'Global.to_static={dy2st}'])
  212. def _update_use_vdl(self, use_vdl: bool):
  213. """update config to set VisualDL
  214. Args:
  215. use_vdl (bool): whether or not to use VisualDL.
  216. """
  217. self.update([f'Global.use_visualdl={use_vdl}'])
  218. def _update_epochs(self, epochs: int):
  219. """update epochs setting
  220. Args:
  221. epochs (int): the epochs number value to set
  222. """
  223. self.update([f'Global.epochs={epochs}'])
  224. def _update_checkpoints(self, resume_path: Union[None, str]):
  225. """update checkpoint setting
  226. Args:
  227. resume_path (None | str): the resume training setting. if is `None`, train from scratch, otherwise,
  228. train from checkpoint file that path is `.pdparams` file.
  229. """
  230. if resume_path is not None:
  231. resume_path = resume_path.replace(".pdparams", "")
  232. self.update([f'Global.checkpoints={resume_path}'])
  233. def _update_output_dir(self, save_dir: str):
  234. """update output directory
  235. Args:
  236. save_dir (str): the path to save outputs.
  237. """
  238. self.update([f'Global.output_dir={abspath(save_dir)}'])
  239. def update_log_interval(self, log_interval: int):
  240. """update log interval(steps)
  241. Args:
  242. log_interval (int): the log interval value to set.
  243. """
  244. self.update([f'Global.print_batch_step={log_interval}'])
  245. def update_eval_interval(self, eval_interval: int):
  246. """update eval interval(epochs)
  247. Args:
  248. eval_interval (int): the eval interval value to set.
  249. """
  250. self.update([f'Global.eval_interval={eval_interval}'])
  251. def update_save_interval(self, save_interval: int):
  252. """update eval interval(epochs)
  253. Args:
  254. save_interval (int): the save interval value to set.
  255. """
  256. self.update([f'Global.save_interval={save_interval}'])
  257. def _update_predict_img(self, infer_img: str, infer_list: str=None):
  258. """update image to be predicted
  259. Args:
  260. infer_img (str): the path to image that to be predicted.
  261. infer_list (str, optional): the path to file that images. Defaults to None.
  262. """
  263. if infer_list:
  264. self.update([f'Infer.infer_list={infer_list}'])
  265. self.update([f'Infer.infer_imgs={infer_img}'])
  266. def _update_save_inference_dir(self, save_inference_dir: str):
  267. """update directory path to save inference model files
  268. Args:
  269. save_inference_dir (str): the directory path to set.
  270. """
  271. self.update(
  272. [f'Global.save_inference_dir={abspath(save_inference_dir)}'])
  273. def _update_inference_model_dir(self, model_dir: str):
  274. """update inference model directory
  275. Args:
  276. model_dir (str): the directory path of inference model fils that used to predict.
  277. """
  278. self.update([f'Global.inference_model_dir={abspath(model_dir)}'])
  279. def _update_infer_img(self, infer_img: str):
  280. """update path of image that would be predict
  281. Args:
  282. infer_img (str): the image path.
  283. """
  284. self.update([f'Global.infer_imgs={infer_img}'])
  285. def _update_infer_device(self, device: str):
  286. """update the device used in predicting
  287. Args:
  288. device (str): the running device setting
  289. """
  290. self.update([f'Global.use_gpu={device.split(":")[0]=="gpu"}'])
  291. def _update_enable_mkldnn(self, enable_mkldnn: bool):
  292. """update whether to enable MKLDNN
  293. Args:
  294. enable_mkldnn (bool): `True` is enable, otherwise is disable.
  295. """
  296. self.update([f'Global.enable_mkldnn={enable_mkldnn}'])
  297. def _update_infer_img_shape(self, img_shape: str):
  298. """update image cropping shape in the preprocessing
  299. Args:
  300. img_shape (str): the shape of cropping in the preprocessing,
  301. i.e. `PreProcess.transform_ops.1.CropImage.size`.
  302. """
  303. self.update([f'PreProcess.transform_ops.1.CropImage.size={img_shape}'])
  304. def _update_save_predict_result(self, save_dir: str):
  305. """update directory that save predicting output
  306. Args:
  307. save_dir (str): the dicrectory path that save predicting output.
  308. """
  309. self.update([f'Infer.save_dir={save_dir}'])
  310. def update_model(self, **kwargs):
  311. """update model settings
  312. """
  313. for k in kwargs:
  314. v = kwargs[k]
  315. self.update([f'Arch.{k}={v}'])
  316. def update_teacher_model(self, **kwargs):
  317. """update teacher model settings
  318. """
  319. for k in kwargs:
  320. v = kwargs[k]
  321. self.update([f'Arch.models.0.Teacher.{k}={v}'])
  322. def update_student_model(self, **kwargs):
  323. """update student model settings
  324. """
  325. for k in kwargs:
  326. v = kwargs[k]
  327. self.update([f'Arch.models.1.Student.{k}={v}'])
  328. def get_epochs_iters(self) -> int:
  329. """get epochs
  330. Returns:
  331. int: the epochs value, i.e., `Global.epochs` in config.
  332. """
  333. return self.dict['Global']['epochs']
  334. def get_log_interval(self) -> int:
  335. """get log interval(steps)
  336. Returns:
  337. int: the log interval value, i.e., `Global.print_batch_step` in config.
  338. """
  339. return self.dict['Global']['print_batch_step']
  340. def get_eval_interval(self) -> int:
  341. """get eval interval(epochs)
  342. Returns:
  343. int: the eval interval value, i.e., `Global.eval_interval` in config.
  344. """
  345. return self.dict['Global']['eval_interval']
  346. def get_save_interval(self) -> int:
  347. """get save interval(epochs)
  348. Returns:
  349. int: the save interval value, i.e., `Global.save_interval` in config.
  350. """
  351. return self.dict['Global']['save_interval']
  352. def get_learning_rate(self) -> float:
  353. """get learning rate
  354. Returns:
  355. float: the learning rate value, i.e., `Optimizer.lr.learning_rate` in config.
  356. """
  357. return self.dict['Optimizer']['lr']['learning_rate']
  358. def get_warmup_epochs(self) -> int:
  359. """get warmup epochs
  360. Returns:
  361. int: the warmup epochs value, i.e., `Optimizer.lr.warmup_epochs` in config.
  362. """
  363. return self.dict['Optimizer']['lr']['warmup_epoch']
  364. def get_label_dict_path(self) -> str:
  365. """get label dict file path
  366. Returns:
  367. str: the label dict file path, i.e., `PostProcess.Topk.class_id_map_file` in config.
  368. """
  369. return self.dict['PostProcess']['Topk']['class_id_map_file']
  370. def get_batch_size(self, mode='train') -> int:
  371. """get batch size
  372. Args:
  373. mode (str, optional): the mode that to be get batch size value, must be one of 'train', 'eval', 'test'.
  374. Defaults to 'train'.
  375. Returns:
  376. int: the batch size value of `mode`, i.e., `DataLoader.{mode}.sampler.batch_size` in config.
  377. """
  378. return self.dict['DataLoader']['Train']['sampler']['batch_size']
  379. def get_qat_epochs_iters(self) -> int:
  380. """get qat epochs
  381. Returns:
  382. int: the epochs value.
  383. """
  384. return self.get_epochs_iters()
  385. def get_qat_learning_rate(self) -> float:
  386. """get qat learning rate
  387. Returns:
  388. float: the learning rate value.
  389. """
  390. return self.get_learning_rate()
  391. def _get_arch_name(self) -> str:
  392. """get architecture name of model
  393. Returns:
  394. str: the model arch name, i.e., `Arch.name` in config.
  395. """
  396. return self.dict["Arch"]["name"]
  397. def _get_dataset_root(self) -> str:
  398. """get root directory of dataset, i.e. `DataLoader.Train.dataset.image_root`
  399. Returns:
  400. str: the root directory of dataset
  401. """
  402. return self.dict["DataLoader"]["Train"]['dataset']['image_root']
  403. def get_train_save_dir(self) -> str:
  404. """get the directory to save output
  405. Returns:
  406. str: the directory to save output
  407. """
  408. return self['Global']['output_dir']