Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#716 Fix mapilliary_dataset yaml

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:hotfix/SG-000-fix_mapilliary_dataset
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
  1. import abc
  2. from copy import deepcopy
  3. from collections import defaultdict
  4. from typing import Mapping, Iterable, Set, Union
  5. __all__ = ["raise_if_unused_params", "warn_if_unused_params", "UnusedConfigParamException"]
  6. from omegaconf import ListConfig, DictConfig
  7. from super_gradients.common.abstractions.abstract_logger import get_logger
  8. from super_gradients.training.utils import HpmStruct
  9. logger = get_logger(__name__)
  10. class UnusedConfigParamException(Exception):
  11. pass
  12. class AccessCounterMixin:
  13. """
  14. Implements access counting mechanism for configuration settings (dicts/lists).
  15. It is achieved by wrapping underlying config and override __getitem__, __getattr__ methods to catch read operations
  16. and increments access counter for each property.
  17. """
  18. _access_counter: Mapping[str, int]
  19. _prefix: str # Prefix string
  20. def maybe_wrap_as_counter(self, value, key, count_usage: bool = True):
  21. """
  22. Return an attribute value optionally wrapped as access counter adapter to trace read counts.
  23. Args:
  24. value: Attribute value
  25. key: Attribute name
  26. count_usage: Whether increment usage count for given attribute. Default is True.
  27. Returns:
  28. """
  29. key_with_prefix = self._prefix + str(key)
  30. if count_usage:
  31. self._access_counter[key_with_prefix] += 1
  32. if isinstance(value, Mapping):
  33. return AccessCounterDict(value, access_counter=self._access_counter, prefix=key_with_prefix + ".")
  34. if isinstance(value, Iterable) and not isinstance(value, str):
  35. return AccessCounterList(value, access_counter=self._access_counter, prefix=key_with_prefix + ".")
  36. return value
  37. @property
  38. def access_counter(self):
  39. return self._access_counter
  40. @abc.abstractmethod
  41. def get_all_params(self) -> Set[str]:
  42. raise NotImplementedError()
  43. def get_used_params(self) -> Set[str]:
  44. used_params = {k for (k, v) in self._access_counter.items() if v > 0}
  45. return used_params
  46. def get_unused_params(self) -> Set[str]:
  47. unused_params = self.get_all_params() - self.get_used_params()
  48. return unused_params
  49. def __copy__(self):
  50. cls = self.__class__
  51. result = cls.__new__(cls)
  52. result.__dict__.update(self.__dict__)
  53. return result
  54. def __deepcopy__(self, memo):
  55. cls = self.__class__
  56. result = cls.__new__(cls)
  57. memo[id(self)] = result
  58. for k, v in self.__dict__.items():
  59. setattr(result, k, deepcopy(v, memo))
  60. return result
  61. class AccessCounterDict(Mapping, AccessCounterMixin):
  62. def __init__(self, config: Union[dict, DictConfig], access_counter: Mapping[str, int] = None, prefix: str = ""):
  63. super().__init__()
  64. self.config = config
  65. self._access_counter = access_counter or defaultdict(int)
  66. self._prefix = str(prefix)
  67. def __iter__(self):
  68. return self.config.__iter__()
  69. def __len__(self):
  70. return self.config.__len__()
  71. def __getitem__(self, item):
  72. return self.get(item)
  73. def __getattr__(self, item):
  74. value = self.config.__getitem__(item)
  75. return self.maybe_wrap_as_counter(value, item)
  76. def __setitem__(self, key, value):
  77. self.config[key] = value
  78. def __repr__(self):
  79. return self.config.__repr__()
  80. def __str__(self):
  81. return self.config.__str__()
  82. def get(self, item, default=None):
  83. value = self.config.get(item, default)
  84. return self.maybe_wrap_as_counter(value, item)
  85. def get_all_params(self) -> Set[str]:
  86. keys = []
  87. for key, value in self.config.items():
  88. keys.append(self._prefix + str(key))
  89. value = self.maybe_wrap_as_counter(value, key, count_usage=False)
  90. if isinstance(value, AccessCounterMixin):
  91. keys += value.get_all_params()
  92. return set(keys)
  93. class AccessCounterHpmStruct(Mapping, AccessCounterMixin):
  94. def __init__(self, config: HpmStruct, access_counter: Mapping[str, int] = None, prefix: str = ""):
  95. super().__init__()
  96. self.config = config
  97. self._access_counter = access_counter or defaultdict(int)
  98. self._prefix = str(prefix)
  99. def __iter__(self):
  100. return self.config.__dict__.__iter__()
  101. def __len__(self):
  102. return self.config.__dict__.__len__()
  103. def __repr__(self):
  104. return self.config.__repr__()
  105. def __str__(self):
  106. return self.config.__str__()
  107. def __getitem__(self, item):
  108. value = self.config.__dict__[item]
  109. return self.maybe_wrap_as_counter(value, item)
  110. def __getattr__(self, item):
  111. value = self.config.__dict__[item]
  112. return self.maybe_wrap_as_counter(value, item)
  113. def __setitem__(self, key, value):
  114. self.config[key] = value
  115. def get(self, item, default=None):
  116. value = self.config.__dict__.get(item, default)
  117. return self.maybe_wrap_as_counter(value, item)
  118. def get_all_params(self) -> Set[str]:
  119. keys = []
  120. for key, value in self.config.__dict__.items():
  121. # Exclude schema field from params
  122. if key == "schema":
  123. continue
  124. keys.append(self._prefix + str(key))
  125. value = self.maybe_wrap_as_counter(value, key, count_usage=False)
  126. if isinstance(value, AccessCounterMixin):
  127. keys += value.get_all_params()
  128. return set(keys)
  129. class AccessCounterList(list, AccessCounterMixin):
  130. def __init__(self, config: Iterable, access_counter: Mapping[str, int] = None, prefix: str = ""):
  131. super().__init__(config)
  132. self._access_counter = access_counter or defaultdict(int)
  133. self._prefix = str(prefix)
  134. def __iter__(self):
  135. for index, value in enumerate(super().__iter__()):
  136. yield self.maybe_wrap_as_counter(value, index)
  137. def __getitem__(self, item):
  138. value = super().__getitem__(item)
  139. return self.maybe_wrap_as_counter(value, item)
  140. def get_all_params(self) -> Set[str]:
  141. keys = []
  142. for index, value in enumerate(super().__iter__()):
  143. keys.append(self._prefix + str(index))
  144. value = self.maybe_wrap_as_counter(value, index, count_usage=False)
  145. if isinstance(value, AccessCounterMixin):
  146. keys += value.get_all_params()
  147. return set(keys)
  148. class ConfigInspector:
  149. def __init__(self, wrapped_config, unused_params_action: str):
  150. self.wrapped_config = wrapped_config
  151. self.unused_params_action = unused_params_action
  152. def __enter__(self):
  153. return self.wrapped_config
  154. def __exit__(self, exc_type, exc_val, exc_tb):
  155. if exc_type is not None:
  156. raise
  157. unused_params = self.wrapped_config.get_unused_params()
  158. if len(unused_params):
  159. message = f"Detected unused parameters in configuration object that were not consumed by caller: {unused_params}"
  160. if self.unused_params_action == "raise":
  161. raise UnusedConfigParamException(message)
  162. elif self.unused_params_action == "warn":
  163. logger.warning(message)
  164. elif self.unused_params_action == "ignore":
  165. pass
  166. else:
  167. raise KeyError(f"Encountered unknown action key {self.unused_params_action}")
  168. def raise_if_unused_params(config: Union[HpmStruct, DictConfig, ListConfig, Mapping, list, tuple]) -> ConfigInspector:
  169. """
  170. A helper function to check whether all confuration parameters were used on given block of code. Motivation to have
  171. this check is to ensure there were no typo or outdated configuration parameters.
  172. It at least one of config parameters was not used, this function will raise an UnusedConfigParamException exception.
  173. Example usage:
  174. >>> from super_gradients.training.utils import raise_if_unused_params
  175. >>>
  176. >>> with raise_if_unused_params(some_config) as some_config:
  177. >>> do_something_with_config(some_config)
  178. >>>
  179. :param config: A config to check
  180. :return: An instance of ConfigInspector
  181. """
  182. if isinstance(config, HpmStruct):
  183. wrapper_cls = AccessCounterHpmStruct
  184. elif isinstance(config, (Mapping, DictConfig)):
  185. wrapper_cls = AccessCounterDict
  186. elif isinstance(config, (list, tuple, ListConfig)):
  187. wrapper_cls = AccessCounterList
  188. else:
  189. raise RuntimeError(f"Unsupported type. Root configuration object must be a mapping or list. Got type {type(config)}")
  190. return ConfigInspector(wrapper_cls(config), unused_params_action="raise")
  191. def warn_if_unused_params(config):
  192. """
  193. A helper function to check whether all confuration parameters were used on given block of code. Motivation to have
  194. this check is to ensure there were no typo or outdated configuration parameters.
  195. It at least one of config parameters was not used, this function will emit warning.
  196. Example usage:
  197. >>> from super_gradients.training.utils import warn_if_unused_params
  198. >>>
  199. >>> with warn_if_unused_params(some_config) as some_config:
  200. >>> do_something_with_config(some_config)
  201. >>>
  202. :param config: A config to check
  203. :return: An instance of ConfigInspector
  204. """
  205. if isinstance(config, HpmStruct):
  206. wrapper_cls = AccessCounterHpmStruct
  207. elif isinstance(config, (Mapping, DictConfig)):
  208. wrapper_cls = AccessCounterDict
  209. elif isinstance(config, (list, tuple, ListConfig)):
  210. wrapper_cls = AccessCounterList
  211. else:
  212. raise RuntimeError("Unsupported type. Root configuration object must be a mapping or list.")
  213. return ConfigInspector(wrapper_cls(config), unused_params_action="warn")
Discard
Tip!

Press p or to see the previous file or, n or to see the next file