config_helper.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 copy
  16. import collections.abc
  17. import yaml
  18. class PPDetConfigMixin(object):
  19. """ PPDetConfigMixin """
  20. def load_config_literally(self, config_path):
  21. """ load_config_literally """
  22. # Adapted from
  23. # https://github.com/PaddlePaddle/PaddleDetection/blob/e3f8dd16bffca04060ec1edc388c5a618e15bbf8/ppdet/core/workspace.py#L77
  24. # XXX: This function relies on implementation details of PaddleDetection.
  25. BASE_KEY = '_BASE_'
  26. with open(config_path, 'r', encoding='utf-8') as f:
  27. dic = yaml.load(f, Loader=_PPDetSerializableLoader)
  28. if not isinstance(dic, dict):
  29. raise TypeError
  30. if BASE_KEY in dic:
  31. all_base_cfg = dict()
  32. base_ymls = list(dic[BASE_KEY])
  33. for base_yml in base_ymls:
  34. if base_yml.startswith("~"):
  35. base_yml = os.path.expanduser(base_yml)
  36. if not base_yml.startswith('/'):
  37. base_yml = os.path.join(
  38. os.path.dirname(config_path), base_yml)
  39. with open(base_yml, 'r', encoding='utf-8') as f:
  40. base_cfg = self.load_config_literally(base_yml)
  41. all_base_cfg = merge_dicts(base_cfg, all_base_cfg)
  42. del dic[BASE_KEY]
  43. return merge_dicts(dic, all_base_cfg)
  44. return dic
  45. def dump_literal_config(self, config_path, dic):
  46. """ dump_literal_config """
  47. with open(config_path, 'w', encoding='utf-8') as f:
  48. # XXX: We make an extra copy here by calling `dict()`
  49. # to ensure that `dic` can be represented.
  50. yaml.dump(dict(dic), f, Dumper=_PPDetSerializableDumper)
  51. def update_from_dict(self, src_dic, dst_dic):
  52. """ update_from_dict """
  53. return merge_dicts(src_dic, dst_dic)
  54. class _PPDetSerializableHandler(collections.abc.MutableMapping):
  55. """ _PPDetSerializableHandler """
  56. TYPE_KEY = '_type_'
  57. EMPTY_TAG = object()
  58. def __init__(self, tag=None, dic=None):
  59. super().__init__()
  60. if tag is None:
  61. tag = self.EMPTY_TAG
  62. if dic is None:
  63. dic = dict()
  64. self.tag = tag
  65. self.dic = dic
  66. def __repr__(self):
  67. # TODO: Prettier format
  68. return repr({self.TYPE_KEY: self.tag, ** self.dic})
  69. def __getitem__(self, key):
  70. if key == self.TYPE_KEY:
  71. return self.tag
  72. else:
  73. return self.dic[key]
  74. def __setitem__(self, key, val):
  75. if key == self.TYPE_KEY:
  76. self.tag = val
  77. else:
  78. self.dic[key] = val
  79. def __delitem__(self, key):
  80. if key == self.TYPE_KEY:
  81. self.tag = self.EMPTY_TAG
  82. else:
  83. del self.dic[key]
  84. def __len__(self):
  85. return len(self.dic) + 1
  86. def __iter__(self):
  87. if self.has_nonempty_tag():
  88. yield self.TYPE_KEY
  89. yield from self.dic
  90. def has_nonempty_tag(self):
  91. """ has_nonempty_tag """
  92. return self.tag != self.EMPTY_TAG
  93. @classmethod
  94. def is_convertible(cls, obj):
  95. """ is_convertible """
  96. if isinstance(obj, cls):
  97. return False
  98. elif isinstance(obj, collections.abc.Mapping):
  99. return cls.TYPE_KEY in obj
  100. else:
  101. return False
  102. @classmethod
  103. def build_from_dict(cls, dic):
  104. """ build_from_dict """
  105. dic = copy.deepcopy(dic)
  106. tag = dic.pop(cls.TYPE_KEY)
  107. return cls(tag=tag, dic=dic)
  108. def merge_dicts(src_dic, dst_dic):
  109. """ merge_dicts """
  110. # Refer to
  111. # https://github.com/PaddlePaddle/PaddleDetection/blob/e3f8dd16bffca04060ec1edc388c5a618e15bbf8/ppdet/core/workspace.py#L121
  112. # Additionally, this function deals with the case when `src_dic`
  113. # or `dst_dic` contains `_PPDetSerializableHandler` objects.
  114. def _update_sohandler(src_handler, dst_handler):
  115. """ _update_sohandler """
  116. dst_handler.update(src_handler)
  117. def _convert_to_sohandler_if_possible(obj):
  118. """ _convert_to_sohandler_if_possible """
  119. if _PPDetSerializableHandler.is_convertible(obj):
  120. return _PPDetSerializableHandler.build_from_dict(obj)
  121. else:
  122. return obj
  123. def _convert_dict_to_sohandler_with_tag(dic, tag):
  124. """ _convert_dict_to_sohandler_with_tag """
  125. return _PPDetSerializableHandler(tag, dic)
  126. for k, v in src_dic.items():
  127. v = _convert_to_sohandler_if_possible(v)
  128. if k not in dst_dic:
  129. dst_dic[k] = v
  130. else:
  131. dst_dic[k] = _convert_to_sohandler_if_possible(dst_dic[k])
  132. if isinstance(dst_dic[k], _PPDetSerializableHandler):
  133. if isinstance(v, _PPDetSerializableHandler):
  134. _update_sohandler(v, dst_dic[k])
  135. elif isinstance(v, collections.abc.Mapping):
  136. v = _convert_dict_to_sohandler_with_tag(v, dst_dic[k].tag)
  137. _update_sohandler(v, dst_dic[k])
  138. else:
  139. dst_dic[k] = v
  140. elif isinstance(dst_dic[k], collections.abc.Mapping):
  141. if isinstance(v, _PPDetSerializableHandler):
  142. dst_dic[k] = _convert_dict_to_sohandler_with_tag(dst_dic[k],
  143. v.tag)
  144. _update_sohandler(v, dst_dic[k])
  145. elif isinstance(v, collections.abc.Mapping):
  146. merge_dicts(v, dst_dic[k])
  147. else:
  148. dst_dic[k] = v
  149. else:
  150. dst_dic[k] = v
  151. return dst_dic
  152. class _PPDetSerializableConstructor(yaml.constructor.SafeConstructor):
  153. """ _PPDetSerializableConstructor """
  154. def construct_sohandler(self, tag_suffix, node):
  155. """ construct_sohandler """
  156. if not isinstance(node, yaml.nodes.MappingNode):
  157. raise TypeError("Currently, we can only handle a MappingNode.")
  158. mapping = self.construct_mapping(node)
  159. return _PPDetSerializableHandler(tag_suffix, mapping)
  160. class _PPDetSerializableLoader(_PPDetSerializableConstructor,
  161. yaml.loader.SafeLoader):
  162. """ _PPDetSerializableLoader """
  163. def __init__(self, stream):
  164. _PPDetSerializableConstructor.__init__(self)
  165. yaml.loader.SafeLoader.__init__(self, stream)
  166. class _PPDetSerializableRepresenter(yaml.representer.SafeRepresenter):
  167. """ _PPDetSerializableRepresenter """
  168. def represent_sohandler(self, data):
  169. """ represent_sohandler """
  170. # If `data` has empty tag, we represent `data.dic` as a dict
  171. if not data.has_nonempty_tag:
  172. return self.represent_dict(data.dic)
  173. else:
  174. # XXX: Manually represent a serializable object according to the rules defined in
  175. # https://github.com/PaddlePaddle/PaddleDetection/blob/e3f8dd16bffca04060ec1edc388c5a618e15bbf8/ppdet/core/config/yaml_helpers.py#L80
  176. # We prepend a '!' to reconstruct the complete tag
  177. tag = u'!' + data.tag
  178. return self.represent_mapping(tag, data.dic)
  179. class _PPDetSerializableDumper(_PPDetSerializableRepresenter,
  180. yaml.dumper.SafeDumper):
  181. """ _PPDetSerializableDumper """
  182. def __init__(self,
  183. stream,
  184. default_style=None,
  185. default_flow_style=False,
  186. canonical=None,
  187. indent=None,
  188. width=None,
  189. allow_unicode=None,
  190. line_break=None,
  191. encoding=None,
  192. explicit_start=None,
  193. explicit_end=None,
  194. version=None,
  195. tags=None,
  196. sort_keys=True):
  197. _PPDetSerializableRepresenter.__init__(
  198. self,
  199. default_style=default_style,
  200. default_flow_style=default_flow_style,
  201. sort_keys=sort_keys)
  202. yaml.dumper.SafeDumper.__init__(
  203. self,
  204. stream,
  205. default_style=default_style,
  206. default_flow_style=default_flow_style,
  207. canonical=canonical,
  208. indent=indent,
  209. width=width,
  210. allow_unicode=allow_unicode,
  211. line_break=line_break,
  212. encoding=encoding,
  213. explicit_start=explicit_start,
  214. explicit_end=explicit_end,
  215. version=version,
  216. tags=tags,
  217. sort_keys=sort_keys)
  218. def ignore_aliases(self, data):
  219. """ ignore_aliases """
  220. return True
  221. # We note that all custom tags defined in ppdet starts with a '!'.
  222. # We assume that all unknown tags in the config file corresponds to a serializable class defined in ppdet.
  223. _PPDetSerializableLoader.add_multi_constructor(
  224. u'!', _PPDetSerializableConstructor.construct_sohandler)
  225. _PPDetSerializableDumper.add_representer(
  226. _PPDetSerializableHandler,
  227. _PPDetSerializableRepresenter.represent_sohandler)