config.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. from urllib.parse import urlparse
  16. import ruamel.yaml
  17. from paddlets.utils.config import parse_from_yaml, merge_config_dicts
  18. from ...base import BaseConfig
  19. from ....utils.misc import abspath
  20. class BaseTSConfig(BaseConfig):
  21. """Base TS 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_dicts(dict_like_obj, self.dict)
  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_ = parse_from_yaml(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. yaml = ruamel.yaml.YAML()
  46. with open(config_file_path, "w", encoding="utf-8") as f:
  47. yaml.dump(self.dict, f)
  48. def update_epochs(self, epochs: int):
  49. """update epochs setting
  50. Args:
  51. epochs (int): the epochs number value to set
  52. """
  53. self.update({"epoch": epochs})
  54. def update_weights(self, weight_path: str):
  55. """update weight path
  56. Args:
  57. weight_path (str): the local path of weight file to set.
  58. """
  59. self["weights"] = abspath(weight_path)
  60. def update_learning_rate(self, learning_rate: float):
  61. """update learning rate
  62. Args:
  63. learning_rate (float): the learning rate value to set.
  64. Raises:
  65. RuntimeError: Not able to update learning rate, because no LR scheduler config was found.
  66. """
  67. if "learning_rate" not in self.model["model_cfg"]["optimizer_params"]:
  68. raise RuntimeError(
  69. "Not able to update learning rate, because no LR scheduler config was found."
  70. )
  71. self.model["model_cfg"]["optimizer_params"]["learning_rate"] = float(
  72. learning_rate
  73. )
  74. def update_batch_size(self, batch_size: int, mode: str = "train"):
  75. """update batch size setting
  76. Args:
  77. batch_size (int): the batch size number to set.
  78. mode (str, optional): the mode that to be set batch size, must be one of 'train', 'eval', 'test'.
  79. Defaults to 'train'.
  80. Raises:
  81. ValueError: `mode` error. `train` is supported only.
  82. """
  83. if mode == "train":
  84. self.set_val("batch_size", batch_size)
  85. else:
  86. raise ValueError(
  87. f"Setting `batch_size` in {repr(mode)} mode is not supported."
  88. )
  89. def update_pretrained_weights(self, weight_path: str):
  90. """update pretrained weight path
  91. Args:
  92. weight_path (str): the local path or url of pretrained weight file to set.
  93. Raises:
  94. RuntimeError: "Not able to update pretrained weight path, because no model config was found.
  95. TypeError: `weight_path` error. `str` and `None` are supported only.
  96. """
  97. if "model" not in self:
  98. raise RuntimeError(
  99. "Not able to update pretrained weight path, because no model config was found."
  100. )
  101. if isinstance(weight_path, str):
  102. if urlparse(weight_path).scheme == "":
  103. # If `weight_path` is a string but not URL (with scheme present),
  104. # it will be recognized as a local file path.
  105. weight_path = abspath(weight_path)
  106. else:
  107. if weight_path is not None:
  108. raise TypeError("`weight_path` must be string or None.")
  109. self.model["pretrain"] = weight_path
  110. def update_log_ranks(self, device):
  111. """update log ranks
  112. Args:
  113. device (str): the running device to set
  114. """
  115. # PaddleTS does not support multi-device training currently.
  116. pass
  117. def update_print_mem_info(self, print_mem_info: bool):
  118. """setting print memory info"""
  119. assert isinstance(print_mem_info, bool), "print_mem_info should be a bool"
  120. self.update({"print_mem_info": print_mem_info})
  121. def update_dataset(self, dataset_dir: str, dataset_type: str = None):
  122. """update dataset settings"""
  123. raise NotImplementedError
  124. def update_save_dir(self, save_dir: str):
  125. """update save directory
  126. Args:
  127. save_dir (str): the path to save outputs.
  128. """
  129. self["output_dir"] = abspath(save_dir)
  130. def get_epochs_iters(self) -> int:
  131. """get epochs
  132. Returns:
  133. int: the epochs value, i.e., `Global.epochs` in config.
  134. """
  135. if "epoch" in self:
  136. return self.epoch
  137. else:
  138. # Default iters
  139. return 1000
  140. def get_learning_rate(self) -> float:
  141. """get learning rate
  142. Returns:
  143. float: the learning rate value, i.e., `Optimizer.lr.learning_rate` in config.
  144. """
  145. if "learning_rate" not in self.model["model_cfg"]["optimizer_params"]:
  146. # Default lr
  147. return 0.0001
  148. else:
  149. return self.model["model_cfg"]["optimizer_params"]["learning_rate"]
  150. def get_batch_size(self, mode="train") -> int:
  151. """get batch size
  152. Args:
  153. mode (str, optional): the mode that to be get batch size value, must be one of 'train', 'eval', 'test'.
  154. Defaults to 'train'.
  155. Raises:
  156. ValueError: `mode` error. `train` is supported only.
  157. Returns:
  158. int: the batch size value of `mode`, i.e., `DataLoader.{mode}.sampler.batch_size` in config.
  159. """
  160. if mode == "train":
  161. if "batch_size" in self:
  162. return self.batch_size
  163. else:
  164. # Default batch size
  165. return 16
  166. else:
  167. raise ValueError(
  168. f"Getting `batch_size` in {repr(mode)} mode is not supported."
  169. )