config.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import numpy as np
  2. import os
  3. import sys
  4. import platform
  5. import yaml
  6. import time
  7. import shutil
  8. import paddle
  9. import paddle.distributed as dist
  10. from tqdm import tqdm
  11. from argparse import ArgumentParser, RawDescriptionHelpFormatter
  12. from utils import get_logger, print_dict
  13. class ArgsParser(ArgumentParser):
  14. def __init__(self):
  15. super(ArgsParser, self).__init__(
  16. formatter_class=RawDescriptionHelpFormatter)
  17. self.add_argument("-c", "--config", help="configuration file to use")
  18. self.add_argument(
  19. "-o", "--opt", nargs='+', help="set configuration options")
  20. self.add_argument(
  21. '-p',
  22. '--profiler_options',
  23. type=str,
  24. default=None,
  25. help='The option of profiler, which should be in format \"key1=value1;key2=value2;key3=value3\".'
  26. )
  27. def parse_args(self, argv=None):
  28. args = super(ArgsParser, self).parse_args(argv)
  29. assert args.config is not None, \
  30. "Please specify --config=configure_file_path."
  31. args.opt = self._parse_opt(args.opt)
  32. return args
  33. def _parse_opt(self, opts):
  34. config = {}
  35. if not opts:
  36. return config
  37. for s in opts:
  38. s = s.strip()
  39. k, v = s.split('=')
  40. config[k] = yaml.load(v, Loader=yaml.Loader)
  41. return config
  42. class AttrDict(dict):
  43. """Single level attribute dict, NOT recursive"""
  44. def __init__(self, **kwargs):
  45. super(AttrDict, self).__init__()
  46. super(AttrDict, self).update(kwargs)
  47. def __getattr__(self, key):
  48. if key in self:
  49. return self[key]
  50. raise AttributeError("object has no attribute '{}'".format(key))
  51. global_config = AttrDict()
  52. default_config = {'Global': {'debug': False, }}
  53. def load_config(file_path):
  54. """
  55. Load config from yml/yaml file.
  56. Args:
  57. file_path (str): Path of the config file to be loaded.
  58. Returns: global config
  59. """
  60. merge_config(default_config)
  61. _, ext = os.path.splitext(file_path)
  62. assert ext in ['.yml', '.yaml'], "only support yaml files for now"
  63. merge_config(yaml.load(open(file_path, 'rb'), Loader=yaml.Loader))
  64. return global_config
  65. def merge_config(config):
  66. """
  67. Merge config into global config.
  68. Args:
  69. config (dict): Config to be merged.
  70. Returns: global config
  71. """
  72. for key, value in config.items():
  73. if "." not in key:
  74. if isinstance(value, dict) and key in global_config:
  75. global_config[key].update(value)
  76. else:
  77. global_config[key] = value
  78. else:
  79. sub_keys = key.split('.')
  80. assert (
  81. sub_keys[0] in global_config
  82. ), "the sub_keys can only be one of global_config: {}, but get: {}, please check your running command".format(
  83. global_config.keys(), sub_keys[0])
  84. cur = global_config[sub_keys[0]]
  85. for idx, sub_key in enumerate(sub_keys[1:]):
  86. if idx == len(sub_keys) - 2:
  87. cur[sub_key] = value
  88. else:
  89. cur = cur[sub_key]
  90. def preprocess(is_train=False):
  91. FLAGS = ArgsParser().parse_args()
  92. profiler_options = FLAGS.profiler_options
  93. config = load_config(FLAGS.config)
  94. merge_config(FLAGS.opt)
  95. profile_dic = {"profiler_options": FLAGS.profiler_options}
  96. merge_config(profile_dic)
  97. if is_train:
  98. # save_config
  99. save_model_dir = config['save_model_dir']
  100. os.makedirs(save_model_dir, exist_ok=True)
  101. with open(os.path.join(save_model_dir, 'config.yml'), 'w') as f:
  102. yaml.dump(
  103. dict(config), f, default_flow_style=False, sort_keys=False)
  104. log_file = '{}/train.log'.format(save_model_dir)
  105. else:
  106. log_file = None
  107. logger = get_logger(log_file=log_file)
  108. # check if set use_gpu=True in paddlepaddle cpu version
  109. use_gpu = config['use_gpu']
  110. print_dict(config, logger)
  111. return config, logger
  112. if __name__ == "__main__":
  113. config, logger = preprocess(is_train=False)
  114. # print(config)