config.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 merge_config
  20. class VideoClsConfig(BaseConfig):
  21. """Image Classification Task Config"""
  22. def update(self, dict_like_obj: list):
  23. """update self
  24. Args:
  25. dict_like_obj (list): list 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_ = yaml.load(open(config_file_path, "rb"), Loader=yaml.Loader)
  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 = "VideoClsDataset"
  65. if train_list_path:
  66. train_list_path = f"{train_list_path}"
  67. else:
  68. train_list_path = f"{dataset_path}/train.txt"
  69. if dataset_type in ["VideoClsDataset"]:
  70. _cfg = {
  71. "DATASET.train.format": "VideoDataset",
  72. "DATASET.train.data_prefix": dataset_path,
  73. "DATASET.train.file_path": train_list_path,
  74. "DATASET.valid.format": "VideoDataset",
  75. "DATASET.valid.data_prefix": dataset_path,
  76. "DATASET.valid.file_path": os.path.join(dataset_path, "val.txt"),
  77. "DATASET.test.format": "VideoDataset",
  78. "DATASET.test.data_prefix": dataset_path,
  79. "DATASET.test.file_path": os.path.join(dataset_path, "val.txt"),
  80. "Infer.PostProcess.class_id_map_file": os.path.join(
  81. dataset_path, "label.txt"
  82. ),
  83. }
  84. else:
  85. raise ValueError(f"{repr(dataset_type)} is not supported.")
  86. self.update(_cfg)
  87. def update_batch_size(self, batch_size: int, mode: str = "train"):
  88. """update batch size setting
  89. Args:
  90. batch_size (int): the batch size number to set.
  91. mode (str, optional): the mode that to be set batch size, must be one of 'train', 'eval', 'test'.
  92. Defaults to 'train'.
  93. Raises:
  94. ValueError: `mode` error.
  95. """
  96. if mode == "train":
  97. _cfg = {"DATASET.batch_size": batch_size}
  98. elif mode == "eval":
  99. _cfg = {"DATASET.test_batch_size": batch_size}
  100. elif mode == "test":
  101. _cfg = {"DATASET.test_batch_size": batch_size}
  102. else:
  103. raise ValueError("The input `mode` should be train, eval or test.")
  104. self.update(_cfg)
  105. def update_learning_rate(self, learning_rate: float):
  106. """update learning rate
  107. Args:
  108. learning_rate (float): the learning rate value to set.
  109. """
  110. if (
  111. self._dict["OPTIMIZER"]["learning_rate"].get("cosine_base_lr", None)
  112. is not None
  113. ):
  114. _cfg = {"OPTIMIZER.learning_rate.cosine_base_lr": learning_rate}
  115. else:
  116. raise ValueError("unsupported lr format")
  117. self.update(_cfg)
  118. def update_warmup_epochs(self, warmup_epochs: int):
  119. """update warmup epochs
  120. Args:
  121. warmup_epochs (int): the warmup epochs value to set.
  122. """
  123. _cfg = {"OPTIMIZER.learning_rate.warmup_epochs": warmup_epochs}
  124. self.update(_cfg)
  125. def update_pretrained_weights(self, pretrained_model: str):
  126. """update pretrained weight path
  127. Args:
  128. pretrained_model (str): the local path or url of pretrained weight file to set.
  129. """
  130. assert isinstance(
  131. pretrained_model, (str, type(None))
  132. ), "The 'pretrained_model' should be a string, indicating the path to the '*.pdparams' file, or 'None', \
  133. indicating that no pretrained model to be used."
  134. if pretrained_model is None:
  135. self.update({"Global.pretrained_model", None})
  136. else:
  137. if pretrained_model.lower() == "default":
  138. self.update({"Global.pretrained_model", None})
  139. else:
  140. if not pretrained_model.startswith(("http://", "https://")):
  141. pretrained_model = abspath(pretrained_model)
  142. self.update({"Global.pretrained_model": pretrained_model})
  143. def update_num_classes(self, num_classes: int):
  144. """update classes number
  145. Args:
  146. num_classes (int): the classes number value to set.
  147. """
  148. if self._dict["model_name"] == "ppTSMv2":
  149. update_str_list = {"MODEL.backbone.class_num": num_classes}
  150. self.update(update_str_list)
  151. else:
  152. update_str_list = {"MODEL.head.num_classes": num_classes}
  153. self.update(update_str_list)
  154. def _update_slim_config(self, slim_config_path: str):
  155. """update slim settings
  156. Args:
  157. slim_config_path (str): the path to slim config yaml file.
  158. """
  159. slim_config = yaml.load(open(slim_config_path, "rb"), Loader=yaml.Loader)[
  160. "Slim"
  161. ]
  162. self.update({"Slim": slim_config})
  163. def _update_amp(self, amp: Union[None, str]):
  164. """update AMP settings
  165. Args:
  166. amp (None | str): the AMP settings.
  167. Raises:
  168. ValueError: AMP setting `amp` error, missing field `AMP`.
  169. """
  170. if amp is None or amp == "OFF":
  171. if "AMP" in self.dict:
  172. self._dict.pop("AMP")
  173. else:
  174. if "AMP" not in self.dict:
  175. raise ValueError("Config must have AMP information.")
  176. _cfg = {"AMP.use_amp": True, "AMP.level": amp}
  177. self.update(_cfg)
  178. def update_num_workers(self, num_workers: int):
  179. """update workers number of train and eval dataloader
  180. Args:
  181. num_workers (int): the value of train and eval dataloader workers number to set.
  182. """
  183. _cfg = {
  184. "DATASET.num_workers": num_workers,
  185. }
  186. self.update(_cfg)
  187. def update_shared_memory(self, shared_memeory: bool):
  188. """update shared memory setting of train and eval dataloader
  189. Args:
  190. shared_memeory (bool): whether or not to use shared memory
  191. """
  192. assert isinstance(shared_memeory, bool), "shared_memeory should be a bool"
  193. _cfg = [
  194. f"DataLoader.Train.loader.use_shared_memory={shared_memeory}",
  195. f"DataLoader.Eval.loader.use_shared_memory={shared_memeory}",
  196. ]
  197. self.update(_cfg)
  198. def update_shuffle(self, shuffle: bool):
  199. """update shuffle setting of train and eval dataloader
  200. Args:
  201. shuffle (bool): whether or not to shuffle the data
  202. """
  203. assert isinstance(shuffle, bool), "shuffle should be a bool"
  204. _cfg = [
  205. f"DataLoader.Train.loader.shuffle={shuffle}",
  206. f"DataLoader.Eval.loader.shuffle={shuffle}",
  207. ]
  208. self.update(_cfg)
  209. def update_dali(self, dali: bool):
  210. """enable DALI setting of train and eval dataloader
  211. Args:
  212. dali (bool): whether or not to use DALI
  213. """
  214. assert isinstance(dali, bool), "dali should be a bool"
  215. _cfg = [
  216. f"Global.use_dali={dali}",
  217. f"Global.use_dali={dali}",
  218. ]
  219. self.update(_cfg)
  220. def update_seed(self, seed: int):
  221. """update seed
  222. Args:
  223. seed (int): the random seed value to set
  224. """
  225. _cfg = {"Global.seed": seed}
  226. self.update(_cfg)
  227. def update_device(self, device: str):
  228. """update device setting
  229. Args:
  230. device (str): the running device to set
  231. """
  232. device = device.split(":")[0]
  233. _cfg = {"Global.device": device}
  234. self.update(_cfg)
  235. def update_label_dict_path(self, dict_path: str):
  236. """update label dict file path
  237. Args:
  238. dict_path (str): the path of label dict file to set
  239. """
  240. _cfg = {
  241. "PostProcess.Topk.class_id_map_file": {abspath(dict_path)},
  242. }
  243. self.update(_cfg)
  244. def _update_to_static(self, dy2st: bool):
  245. """update config to set dynamic to static mode
  246. Args:
  247. dy2st (bool): whether or not to use the dynamic to static mode.
  248. """
  249. self.update({"to_static": dy2st})
  250. def _update_use_vdl(self, use_vdl: bool):
  251. """update config to set VisualDL
  252. Args:
  253. use_vdl (bool): whether or not to use VisualDL.
  254. """
  255. self.update({"Global.use_visuald": use_vdl})
  256. def _update_epochs(self, epochs: int):
  257. """update epochs setting
  258. Args:
  259. epochs (int): the epochs number value to set
  260. """
  261. self.update({"epochs": epochs})
  262. def _update_checkpoints(self, resume_path: Union[None, str]):
  263. """update checkpoint setting
  264. Args:
  265. resume_path (None | str): the resume training setting. if is `None`, train from scratch, otherwise,
  266. train from checkpoint file that path is `.pdparams` file.
  267. """
  268. if resume_path is not None:
  269. resume_path = resume_path.replace(".pdparams", "")
  270. self.update({"Global.checkpoints": resume_path})
  271. def _update_output_dir(self, save_dir: str):
  272. """update output directory
  273. Args:
  274. save_dir (str): the path to save outputs.
  275. """
  276. self.update({"output_dir": abspath(save_dir)})
  277. def update_log_interval(self, log_interval: int):
  278. """update log interval(steps)
  279. Args:
  280. log_interval (int): the log interval value to set.
  281. """
  282. self.update({"log_interval": log_interval})
  283. def update_eval_interval(self, eval_interval: int):
  284. """update eval interval(epochs)
  285. Args:
  286. eval_interval (int): the eval interval value to set.
  287. """
  288. self.update({"val_interval": eval_interval})
  289. def update_save_interval(self, save_interval: int):
  290. """update eval interval(epochs)
  291. Args:
  292. save_interval (int): the save interval value to set.
  293. """
  294. self.update({"save_interval": save_interval})
  295. def update_log_ranks(self, device):
  296. """update log ranks
  297. Args:
  298. device (str): the running device to set
  299. """
  300. log_ranks = device.split(":")[1]
  301. self.update({"Global.log_ranks": log_ranks})
  302. def update_print_mem_info(self, print_mem_info: bool):
  303. """setting print memory info"""
  304. assert isinstance(print_mem_info, bool), "print_mem_info should be a bool"
  305. self.update({"Global.print_mem_info": print_mem_info})
  306. def _update_predict_video(self, infer_video: str, infer_list: str = None):
  307. """update video to be predicted
  308. Args:
  309. infer_video (str): the path to image that to be predicted.
  310. infer_list (str, optional): the path to file that videos. Defaults to None.
  311. """
  312. if infer_list:
  313. self.update({"Infer.infer_list": infer_list})
  314. self.update({"Infer.infer_videos": infer_video})
  315. def _update_save_inference_dir(self, save_inference_dir: str):
  316. """update directory path to save inference model files
  317. Args:
  318. save_inference_dir (str): the directory path to set.
  319. """
  320. self.update({"Global.save_inference_dir": abspath(save_inference_dir)})
  321. def _update_inference_model_dir(self, model_dir: str):
  322. """update inference model directory
  323. Args:
  324. model_dir (str): the directory path of inference model fils that used to predict.
  325. """
  326. self.update({"Global.inference_model_dir": abspath(model_dir)})
  327. def _update_infer_video(self, infer_video: str):
  328. """update path of image that would be predict
  329. Args:
  330. infer_video (str): the image path.
  331. """
  332. self.update({"Global.infer_videos": infer_video})
  333. def _update_infer_device(self, device: str):
  334. """update the device used in predicting
  335. Args:
  336. device (str): the running device setting
  337. """
  338. self.update({"Global.use_gpu": device.split(":")[0] == "gpu"})
  339. def _update_enable_mkldnn(self, enable_mkldnn: bool):
  340. """update whether to enable MKLDNN
  341. Args:
  342. enable_mkldnn (bool): `True` is enable, otherwise is disable.
  343. """
  344. self.update({"Global.enable_mkldnn": enable_mkldnn})
  345. def _update_infer_video_shape(self, img_shape: str):
  346. """update image cropping shape in the preprocessing
  347. Args:
  348. img_shape (str): the shape of cropping in the preprocessing,
  349. i.e. `PreProcess.transform_ops.1.CropImage.size`.
  350. """
  351. self.update({"INFERENCE.target_size": img_shape})
  352. def _update_save_predict_result(self, save_dir: str):
  353. """update directory that save predicting output
  354. Args:
  355. save_dir (str): the directory path that save predicting output.
  356. """
  357. self.update({"Infer.save_dir": save_dir})
  358. def get_epochs_iters(self) -> int:
  359. """get epochs
  360. Returns:
  361. int: the epochs value, i.e., `Global.epochs` in config.
  362. """
  363. return self.dict["Global"]["epochs"]
  364. def get_log_interval(self) -> int:
  365. """get log interval(steps)
  366. Returns:
  367. int: the log interval value, i.e., `Global.print_batch_step` in config.
  368. """
  369. return self.dict["Global"]["print_batch_step"]
  370. def get_eval_interval(self) -> int:
  371. """get eval interval(epochs)
  372. Returns:
  373. int: the eval interval value, i.e., `Global.eval_interval` in config.
  374. """
  375. return self.dict["Global"]["eval_interval"]
  376. def get_save_interval(self) -> int:
  377. """get save interval(epochs)
  378. Returns:
  379. int: the save interval value, i.e., `Global.save_interval` in config.
  380. """
  381. return self.dict["Global"]["save_interval"]
  382. def get_learning_rate(self) -> float:
  383. """get learning rate
  384. Returns:
  385. float: the learning rate value, i.e., `Optimizer.lr.learning_rate` in config.
  386. """
  387. return self.dict["Optimizer"]["lr"]["learning_rate"]
  388. def get_warmup_epochs(self) -> int:
  389. """get warmup epochs
  390. Returns:
  391. int: the warmup epochs value, i.e., `Optimizer.lr.warmup_epochs` in config.
  392. """
  393. return self.dict["Optimizer"]["lr"]["warmup_epoch"]
  394. def get_label_dict_path(self) -> str:
  395. """get label dict file path
  396. Returns:
  397. str: the label dict file path, i.e., `PostProcess.Topk.class_id_map_file` in config.
  398. """
  399. return self.dict["PostProcess"]["Topk"]["class_id_map_file"]
  400. def get_batch_size(self, mode="train") -> int:
  401. """get batch size
  402. Args:
  403. mode (str, optional): the mode that to be get batch size value, must be one of 'train', 'eval', 'test'.
  404. Defaults to 'train'.
  405. Returns:
  406. int: the batch size value of `mode`, i.e., `DataLoader.{mode}.sampler.batch_size` in config.
  407. """
  408. return self.dict["DataLoader"]["Train"]["sampler"]["batch_size"]
  409. def get_qat_epochs_iters(self) -> int:
  410. """get qat epochs
  411. Returns:
  412. int: the epochs value.
  413. """
  414. return self.get_epochs_iters()
  415. def get_qat_learning_rate(self) -> float:
  416. """get qat learning rate
  417. Returns:
  418. float: the learning rate value.
  419. """
  420. return self.get_learning_rate()
  421. def _get_arch_name(self) -> str:
  422. """get architecture name of model
  423. Returns:
  424. str: the model arch name, i.e., `Arch.name` in config.
  425. """
  426. return self.dict["Arch"]["name"]
  427. def _get_dataset_root(self) -> str:
  428. """get root directory of dataset, i.e. `DataLoader.Train.dataset.video_root`
  429. Returns:
  430. str: the root directory of dataset
  431. """
  432. return self.dict["DataLoader"]["Train"]["dataset"]["video_root"]
  433. def get_train_save_dir(self) -> str:
  434. """get the directory to save output
  435. Returns:
  436. str: the directory to save output
  437. """
  438. return self["output_dir"]