config_helper.py 9.1 KB

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