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

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
  1. import abc
  2. from collections import defaultdict
  3. from typing import Mapping, Iterable, Set, Union
  4. __all__ = ["raise_if_unused_params", "warn_if_unused_params", "UnusedConfigParamException"]
  5. from omegaconf import ListConfig, DictConfig
  6. from super_gradients.common.abstractions.abstract_logger import get_logger
  7. from super_gradients.training.utils import HpmStruct
  8. logger = get_logger(__name__)
  9. class UnusedConfigParamException(Exception):
  10. pass
  11. class AccessCounterMixin:
  12. """
  13. Implements access counting mechanism for configuration settings (dicts/lists).
  14. It is achieved by wrapping underlying config and override __getitem__, __getattr__ methods to catch read operations
  15. and increments access counter for each property.
  16. """
  17. _access_counter: Mapping[str, int]
  18. _prefix: str # Prefix string
  19. def maybe_wrap_as_counter(self, value, key, count_usage: bool = True):
  20. """
  21. Return an attribute value optionally wrapped as access counter adapter to trace read counts.
  22. Args:
  23. value: Attribute value
  24. key: Attribute name
  25. count_usage: Whether increment usage count for given attribute. Default is True.
  26. Returns:
  27. """
  28. key_with_prefix = self._prefix + str(key)
  29. if count_usage:
  30. self._access_counter[key_with_prefix] += 1
  31. if isinstance(value, Mapping):
  32. return AccessCounterDict(value, access_counter=self._access_counter, prefix=key_with_prefix + ".")
  33. if isinstance(value, Iterable) and not isinstance(value, str):
  34. return AccessCounterList(value, access_counter=self._access_counter, prefix=key_with_prefix + ".")
  35. return value
  36. @property
  37. def access_counter(self):
  38. return self._access_counter
  39. @abc.abstractmethod
  40. def get_all_params(self) -> Set[str]:
  41. raise NotImplementedError()
  42. def get_used_params(self) -> Set[str]:
  43. used_params = {k for (k, v) in self._access_counter.items() if v > 0}
  44. return used_params
  45. def get_unused_params(self) -> Set[str]:
  46. unused_params = self.get_all_params() - self.get_used_params()
  47. return unused_params
  48. class AccessCounterDict(Mapping, AccessCounterMixin):
  49. def __init__(self, config: Mapping, access_counter: Mapping[str, int] = None, prefix: str = ""):
  50. super().__init__()
  51. self.config = config
  52. self._access_counter = access_counter or defaultdict(int)
  53. self._prefix = str(prefix)
  54. def __iter__(self):
  55. return self.config.__iter__()
  56. def __len__(self):
  57. return self.config.__len__()
  58. def __getitem__(self, item):
  59. return self.get(item)
  60. def __getattr__(self, item):
  61. value = self.config.__getitem__(item)
  62. return self.maybe_wrap_as_counter(value, item)
  63. def get(self, item, default=None):
  64. value = self.config.get(item, default)
  65. return self.maybe_wrap_as_counter(value, item)
  66. def get_all_params(self) -> Set[str]:
  67. keys = []
  68. for key, value in self.config.items():
  69. keys.append(self._prefix + str(key))
  70. value = self.maybe_wrap_as_counter(value, key, count_usage=False)
  71. if isinstance(value, AccessCounterMixin):
  72. keys += value.get_all_params()
  73. return set(keys)
  74. class AccessCounterHpmStruct(Mapping, AccessCounterMixin):
  75. def __init__(self, config: HpmStruct, access_counter: Mapping[str, int] = None, prefix: str = ""):
  76. super().__init__()
  77. self.config = config
  78. self._access_counter = access_counter or defaultdict(int)
  79. self._prefix = str(prefix)
  80. def __iter__(self):
  81. return self.config.__dict__.__iter__()
  82. def __len__(self):
  83. return self.config.__dict__.__len__()
  84. def __repr__(self):
  85. return self.config.__repr__()
  86. def __str__(self):
  87. return self.config.__str__()
  88. def __getitem__(self, item):
  89. value = self.config.__dict__[item]
  90. return self.maybe_wrap_as_counter(value, item)
  91. def __getattr__(self, item):
  92. value = self.config.__dict__[item]
  93. return self.maybe_wrap_as_counter(value, item)
  94. def get(self, item, default=None):
  95. value = self.config.__dict__.get(item, default)
  96. return self.maybe_wrap_as_counter(value, item)
  97. def get_all_params(self) -> Set[str]:
  98. keys = []
  99. for key, value in self.config.__dict__.items():
  100. # Exclude schema field from params
  101. if key == "schema":
  102. continue
  103. keys.append(self._prefix + str(key))
  104. value = self.maybe_wrap_as_counter(value, key, count_usage=False)
  105. if isinstance(value, AccessCounterMixin):
  106. keys += value.get_all_params()
  107. return set(keys)
  108. class AccessCounterList(list, AccessCounterMixin):
  109. def __init__(self, config: Iterable, access_counter: Mapping[str, int] = None, prefix: str = ""):
  110. super().__init__(config)
  111. self._access_counter = access_counter or defaultdict(int)
  112. self._prefix = str(prefix)
  113. def __iter__(self):
  114. for index, value in enumerate(super().__iter__()):
  115. yield self.maybe_wrap_as_counter(value, index)
  116. def __getitem__(self, item):
  117. value = super().__getitem__(item)
  118. return self.maybe_wrap_as_counter(value, item)
  119. def get_all_params(self) -> Set[str]:
  120. keys = []
  121. for index, value in enumerate(super().__iter__()):
  122. keys.append(self._prefix + str(index))
  123. value = self.maybe_wrap_as_counter(value, index, count_usage=False)
  124. if isinstance(value, AccessCounterMixin):
  125. keys += value.get_all_params()
  126. return set(keys)
  127. class ConfigInspector:
  128. def __init__(self, wrapped_config, unused_params_action: str):
  129. self.wrapped_config = wrapped_config
  130. self.unused_params_action = unused_params_action
  131. def __enter__(self):
  132. return self.wrapped_config
  133. def __exit__(self, exc_type, exc_val, exc_tb):
  134. unused_params = self.wrapped_config.get_unused_params()
  135. if len(unused_params):
  136. message = f"Detected unused parameters in configuration object that were not consumed by caller: {unused_params}"
  137. if self.unused_params_action == "raise":
  138. raise UnusedConfigParamException(message)
  139. elif self.unused_params_action == "warn":
  140. logger.warning(message)
  141. elif self.unused_params_action == "ignore":
  142. pass
  143. else:
  144. raise KeyError(f"Encountered unknown action key {self.unused_params_action}")
  145. def raise_if_unused_params(config: Union[HpmStruct, DictConfig, ListConfig, Mapping, list, tuple]) -> ConfigInspector:
  146. """
  147. A helper function to check whether all confuration parameters were used on given block of code. Motivation to have
  148. this check is to ensure there were no typo or outdated configuration parameters.
  149. It at least one of config parameters was not used, this function will raise an UnusedConfigParamException exception.
  150. Example usage:
  151. >>> from super_gradients.training.utils import raise_if_unused_params
  152. >>>
  153. >>> with raise_if_unused_params(some_config) as some_config:
  154. >>> do_something_with_config(some_config)
  155. >>>
  156. :param config: A config to check
  157. :return: An instance of ConfigInspector
  158. """
  159. if isinstance(config, HpmStruct):
  160. wrapper_cls = AccessCounterHpmStruct
  161. elif isinstance(config, (Mapping, DictConfig)):
  162. wrapper_cls = AccessCounterDict
  163. elif isinstance(config, (list, tuple, ListConfig)):
  164. wrapper_cls = AccessCounterList
  165. else:
  166. raise RuntimeError(f"Unsupported type. Root configuration object must be a mapping or list. Got type {type(config)}")
  167. return ConfigInspector(wrapper_cls(config), unused_params_action="raise")
  168. def warn_if_unused_params(config):
  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 emit warning.
  173. Example usage:
  174. >>> from super_gradients.training.utils import warn_if_unused_params
  175. >>>
  176. >>> with warn_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("Unsupported type. Root configuration object must be a mapping or list.")
  190. 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