config_helper.py 9.1 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. print(dic)
  30. raise TypeError
  31. if BASE_KEY in dic:
  32. all_base_cfg = dict()
  33. base_ymls = list(dic[BASE_KEY])
  34. for base_yml in base_ymls:
  35. if base_yml.startswith("~"):
  36. base_yml = os.path.expanduser(base_yml)
  37. if not base_yml.startswith("/"):
  38. base_yml = os.path.join(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], v.tag)
  143. _update_sohandler(v, dst_dic[k])
  144. elif isinstance(v, collections.abc.Mapping):
  145. merge_dicts(v, dst_dic[k])
  146. else:
  147. dst_dic[k] = v
  148. else:
  149. dst_dic[k] = v
  150. return dst_dic
  151. class _PPDetSerializableConstructor(yaml.constructor.SafeConstructor):
  152. """_PPDetSerializableConstructor"""
  153. def construct_sohandler(self, tag_suffix, node):
  154. """construct_sohandler"""
  155. if not isinstance(node, yaml.nodes.MappingNode):
  156. raise TypeError("Currently, we can only handle a MappingNode.")
  157. mapping = self.construct_mapping(node)
  158. return _PPDetSerializableHandler(tag_suffix, mapping)
  159. class _PPDetSerializableLoader(_PPDetSerializableConstructor, yaml.loader.SafeLoader):
  160. """_PPDetSerializableLoader"""
  161. def __init__(self, stream):
  162. _PPDetSerializableConstructor.__init__(self)
  163. yaml.loader.SafeLoader.__init__(self, stream)
  164. class _PPDetSerializableRepresenter(yaml.representer.SafeRepresenter):
  165. """_PPDetSerializableRepresenter"""
  166. def represent_sohandler(self, data):
  167. """represent_sohandler"""
  168. # If `data` has empty tag, we represent `data.dic` as a dict
  169. if not data.has_nonempty_tag:
  170. return self.represent_dict(data.dic)
  171. else:
  172. # XXX: Manually represent a serializable object according to the rules defined in
  173. # https://github.com/PaddlePaddle/PaddleDetection/blob/e3f8dd16bffca04060ec1edc388c5a618e15bbf8/ppdet/core/config/yaml_helpers.py#L80
  174. # We prepend a '!' to reconstruct the complete tag
  175. tag = "!" + data.tag
  176. return self.represent_mapping(tag, data.dic)
  177. class _PPDetSerializableDumper(_PPDetSerializableRepresenter, yaml.dumper.SafeDumper):
  178. """_PPDetSerializableDumper"""
  179. def __init__(
  180. self,
  181. stream,
  182. default_style=None,
  183. default_flow_style=False,
  184. canonical=None,
  185. indent=None,
  186. width=None,
  187. allow_unicode=None,
  188. line_break=None,
  189. encoding=None,
  190. explicit_start=None,
  191. explicit_end=None,
  192. version=None,
  193. tags=None,
  194. sort_keys=True,
  195. ):
  196. _PPDetSerializableRepresenter.__init__(
  197. self,
  198. default_style=default_style,
  199. default_flow_style=default_flow_style,
  200. sort_keys=sort_keys,
  201. )
  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. )
  219. def ignore_aliases(self, data):
  220. """ignore_aliases"""
  221. return True
  222. # We note that all custom tags defined in ppdet starts with a '!'.
  223. # We assume that all unknown tags in the config file corresponds to a serializable class defined in ppdet.
  224. _PPDetSerializableLoader.add_multi_constructor(
  225. "!", _PPDetSerializableConstructor.construct_sohandler
  226. )
  227. _PPDetSerializableDumper.add_representer(
  228. _PPDetSerializableHandler, _PPDetSerializableRepresenter.represent_sohandler
  229. )