You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

querier.py 17 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """This file is used to define lineage info querier."""
  16. import enum
  17. import functools
  18. import operator
  19. from mindinsight.lineagemgr.common.exceptions.exceptions import LineageQuerierParamException, LineageParamTypeError
  20. from mindinsight.lineagemgr.common.utils import enum_to_list
  21. from mindinsight.lineagemgr.lineage_parser import SuperLineageObj
  22. from mindinsight.lineagemgr.querier.query_model import FIELD_MAPPING
  23. @enum.unique
  24. class ConditionParam(enum.Enum):
  25. """
  26. Filtering and sorting field names.
  27. `LIMIT` represents the number of lineage info per page. `OFFSET` represents
  28. page number. `SORTED_NAME` means to sort by this field. `SORTED_TYPE` means
  29. ascending or descending.
  30. """
  31. LIMIT = 'limit'
  32. OFFSET = 'offset'
  33. SORTED_NAME = 'sorted_name'
  34. SORTED_TYPE = 'sorted_type'
  35. LINEAGE_TYPE = 'lineage_type'
  36. @classmethod
  37. def is_condition_type(cls, value):
  38. """
  39. Judge that the input param is one of field names in the class.
  40. Args:
  41. value (str): The input field name.
  42. Returns:
  43. bool, `True` if the input field name in the class, else `False`.
  44. """
  45. return value in cls._value2member_map_
  46. @enum.unique
  47. class ExpressionType(enum.Enum):
  48. """
  49. Filter condition name definition.
  50. `EQ` means `==`. `LT` means `<`. `GT` means `>`. `LE` means `<=`. `GE` means
  51. `>=`. `IN` means filter value in the specified list.
  52. """
  53. EQ = 'eq'
  54. LT = 'lt'
  55. GT = 'gt'
  56. LE = 'le'
  57. GE = 'ge'
  58. IN = 'in'
  59. @classmethod
  60. def is_valid_exp(cls, key):
  61. """
  62. Judge that the input param is one of filter condition names in the class.
  63. Args:
  64. key (str): The input filter condition name.
  65. Returns:
  66. bool, `True` if the input filter condition name in the class,
  67. else `False`.
  68. """
  69. return key in cls._value2member_map_
  70. @classmethod
  71. def is_match(cls, except_key, except_value, actual_value):
  72. """
  73. Determine whether the value meets the expected requirement.
  74. Args:
  75. except_key (str): The expression key.
  76. except_value (Union[str, int, float, list, tuple]): The expected
  77. value.
  78. actual_value (Union[str, int, float]): The actual value.
  79. Returns:
  80. bool, `True` if the actual value meets the expected requirement,
  81. else `False`.
  82. """
  83. if actual_value is None and except_key in [cls.LT.value, cls.GT.value,
  84. cls.LE.value, cls.GE.value]:
  85. return False
  86. try:
  87. if except_key == cls.IN.value:
  88. state = operator.contains(except_value, actual_value)
  89. else:
  90. state = getattr(operator, except_key)(actual_value, except_value)
  91. except TypeError:
  92. # actual_value can not compare with except_value
  93. return False
  94. return state
  95. @enum.unique
  96. class LineageFilterKey(enum.Enum):
  97. """Summary lineage information filter key."""
  98. METRIC = 'metric'
  99. HYPER_PARAM = 'hyper_parameters'
  100. ALGORITHM = 'algorithm'
  101. TRAIN_DATASET = 'train_dataset'
  102. VALID_DATASET = 'valid_dataset'
  103. MODEL = 'model'
  104. DATASET_GRAPH = 'dataset_graph'
  105. @classmethod
  106. def is_valid_filter_key(cls, key):
  107. """
  108. Judge that the input param is one of field names in the class.
  109. Args:
  110. key (str): The input field name.
  111. Returns:
  112. bool, `True` if the input field name in the class, else `False`.
  113. """
  114. return key in cls._value2member_map_
  115. @classmethod
  116. def get_key_list(cls):
  117. """
  118. Get the filter key name list.
  119. Returns:
  120. list[str], the filter key name list.
  121. """
  122. return [member.value for member in cls]
  123. @enum.unique
  124. class LineageType(enum.Enum):
  125. """Lineage search type."""
  126. DATASET = 'dataset'
  127. MODEL = 'model'
  128. class Querier:
  129. """
  130. The querier of model lineage information.
  131. The class provides model lineage information query function. The information
  132. includes hyper parameters, train dataset, algorithm, model information,
  133. metric, valid dataset, etc.
  134. The class also provides search and sorting capabilities about model lineage
  135. information. You can search and sort by the specified condition.
  136. The condition explain in `ConditionParam` and `ExpressionType` class.
  137. See the method `filter_summary_lineage` for supported fields.
  138. Args:
  139. super_lineage_objs (dict): A dict of <summary_dir, SuperLineageObject>.
  140. Raises:
  141. LineageParamTypeError: If the input parameter type is invalid.
  142. LineageQuerierParamException: If the input parameter value is invalid.
  143. LineageSummaryParseException: If all summary logs parsing failed.
  144. """
  145. def __init__(self, super_lineage_objs):
  146. self._super_lineage_objs = self._check_objs(super_lineage_objs)
  147. def _check_objs(self, super_lineage_objs):
  148. if super_lineage_objs is None:
  149. raise LineageQuerierParamException(
  150. 'querier_init_param', 'The querier init param is empty.'
  151. )
  152. if not isinstance(super_lineage_objs, dict):
  153. raise LineageParamTypeError("Init param should be a dict.")
  154. return super_lineage_objs
  155. def get_summary_lineage(self, summary_dir=None, filter_keys=None):
  156. """
  157. Get summary lineage information.
  158. If a summary dir is specified, the special summary lineage information
  159. will be found. If the summary dir is `None`, all summary lineage
  160. information will be found.
  161. Returns the content corresponding to the specified field in the filter
  162. key. The contents of the filter key include `metric`, `hyper_parameters`,
  163. `algorithm`, `train_dataset`, `valid_dataset` and `model`. You can
  164. specify multiple filter keys in the `filter_keys`. If the parameter is
  165. `None`, complete information will be returned.
  166. Args:
  167. summary_dir (Union[str, None]): Summary log dir. Default: None.
  168. filter_keys (Union[list[str], None]): Filter keys. Default: None.
  169. Returns:
  170. list[dict], summary lineage information.
  171. """
  172. if filter_keys is None:
  173. filter_keys = LineageFilterKey.get_key_list()
  174. else:
  175. for key in filter_keys:
  176. if not LineageFilterKey.is_valid_filter_key(key):
  177. raise LineageQuerierParamException(
  178. filter_keys, 'The filter key {} is invalid.'.format(key)
  179. )
  180. if summary_dir is None:
  181. result = [
  182. item.lineage_obj.get_summary_info(filter_keys) for item in self._super_lineage_objs.values()
  183. ]
  184. elif summary_dir in self._super_lineage_objs:
  185. lineage_obj = self._super_lineage_objs[summary_dir].lineage_obj
  186. result = [lineage_obj.get_summary_info(filter_keys)]
  187. else:
  188. raise LineageQuerierParamException(
  189. 'summary_dir',
  190. 'Summary dir {} does not exist.'.format(summary_dir)
  191. )
  192. return result
  193. def filter_summary_lineage(self, condition=None, added=False):
  194. """
  195. Filter and sort lineage information based on the specified condition.
  196. See `ConditionType` and `ExpressionType` class for the rule of filtering
  197. and sorting. The filtering and sorting fields are defined in
  198. `FIELD_MAPPING` or prefixed with `metric/` or 'user_defined/'.
  199. If the condition is `None`, all model lineage information will be
  200. returned.
  201. Args:
  202. condition (Union[dict, None]): Filter and sort condition.
  203. Default: None.
  204. Returns:
  205. dict, filtered and sorted model lineage information.
  206. """
  207. def _filter(super_lineage_obj: SuperLineageObj):
  208. for condition_key, condition_value in condition.items():
  209. if ConditionParam.is_condition_type(condition_key):
  210. continue
  211. if self._is_valid_field(condition_key):
  212. raise LineageQuerierParamException(
  213. 'condition',
  214. 'The field {} not supported'.format(condition_key)
  215. )
  216. value = super_lineage_obj.lineage_obj.get_value_by_key(condition_key)
  217. for exp_key, exp_value in condition_value.items():
  218. if not ExpressionType.is_valid_exp(exp_key):
  219. raise LineageQuerierParamException(
  220. 'condition',
  221. 'The expression {} not supported.'.format(exp_key)
  222. )
  223. if not ExpressionType.is_match(exp_key, exp_value, value):
  224. return False
  225. return True
  226. def _cmp(obj1: SuperLineageObj, obj2: SuperLineageObj):
  227. value1 = obj1.lineage_obj.get_value_by_key(sorted_name)
  228. value2 = obj2.lineage_obj.get_value_by_key(sorted_name)
  229. if value1 is None and value2 is None:
  230. cmp_result = 0
  231. elif value1 is None:
  232. cmp_result = -1
  233. elif value2 is None:
  234. cmp_result = 1
  235. else:
  236. try:
  237. cmp_result = (value1 > value2) - (value1 < value2)
  238. except TypeError:
  239. type1 = type(value1).__name__
  240. type2 = type(value2).__name__
  241. cmp_result = (type1 > type2) - (type1 < type2)
  242. return cmp_result
  243. if condition is None:
  244. condition = {}
  245. self._add_dataset_mark()
  246. super_lineage_objs = list(self._super_lineage_objs.values())
  247. super_lineage_objs.sort(key=lambda x: x.update_time, reverse=True)
  248. results = list(filter(_filter, super_lineage_objs))
  249. if ConditionParam.SORTED_NAME.value in condition:
  250. sorted_name = condition.get(ConditionParam.SORTED_NAME.value)
  251. if self._is_valid_field(sorted_name):
  252. raise LineageQuerierParamException(
  253. 'condition',
  254. 'The sorted name {} not supported.'.format(sorted_name)
  255. )
  256. sorted_type = condition.get(ConditionParam.SORTED_TYPE.value)
  257. reverse = sorted_type == 'descending'
  258. results = sorted(
  259. results, key=functools.cmp_to_key(_cmp), reverse=reverse
  260. )
  261. offset_results = self._handle_limit_and_offset(condition, results)
  262. customized = self._organize_customized(offset_results)
  263. lineage_types = condition.get(ConditionParam.LINEAGE_TYPE.value)
  264. lineage_types = self._get_lineage_types(lineage_types)
  265. object_items = []
  266. for item in offset_results:
  267. lineage_object = dict()
  268. if LineageType.MODEL.value in lineage_types:
  269. lineage_object.update(item.lineage_obj.to_model_lineage_dict())
  270. if LineageType.DATASET.value in lineage_types:
  271. lineage_object.update(item.lineage_obj.to_dataset_lineage_dict())
  272. if added:
  273. lineage_object.update({"added_info": item.added_info})
  274. object_items.append(lineage_object)
  275. lineage_info = {
  276. 'customized': customized,
  277. 'object': object_items,
  278. 'count': len(results)
  279. }
  280. return lineage_info
  281. def _organize_customized(self, offset_results):
  282. """Organize customized."""
  283. customized = dict()
  284. for offset_result in offset_results:
  285. for obj_name in ["metric", "user_defined"]:
  286. self._organize_customized_item(customized, offset_result.lineage_obj, obj_name)
  287. # If types contain numbers and string, it will be "mixed".
  288. # If types contain "int" and "float", it will be "float".
  289. for key, value in customized.items():
  290. types = value["type"]
  291. if len(types) == 1:
  292. customized[key]["type"] = list(types)[0]
  293. elif types.issubset(["int", "float"]):
  294. customized[key]["type"] = "float"
  295. else:
  296. customized[key]["type"] = "mixed"
  297. return customized
  298. def _organize_customized_item(self, customized, offset_result, obj_name):
  299. """Organize customized item."""
  300. obj = getattr(offset_result, obj_name)
  301. require = bool(obj_name == "metric")
  302. if obj and isinstance(obj, dict):
  303. for key, value in obj.items():
  304. label = f'{obj_name}/{key}'
  305. current_type = type(value).__name__
  306. if customized.get(label) is None:
  307. customized[label] = dict()
  308. customized[label]["label"] = label
  309. # user defined info is not displayed by default
  310. customized[label]["required"] = require
  311. customized[label]["type"] = set()
  312. customized[label]["type"].add(current_type)
  313. def _get_lineage_types(self, lineage_type_param):
  314. """
  315. Get lineage types.
  316. Args:
  317. lineage_type_param (dict): A dict contains "in" or "eq".
  318. Returns:
  319. list, lineage type.
  320. """
  321. # lineage_type_param is None or an empty dict
  322. if not lineage_type_param:
  323. return enum_to_list(LineageType)
  324. if lineage_type_param.get("in") is not None:
  325. return lineage_type_param.get("in")
  326. return [lineage_type_param.get("eq")]
  327. def _is_valid_field(self, field_name):
  328. """
  329. Check if field name is valid.
  330. Args:
  331. field_name (str): Field name.
  332. Returns:
  333. bool, `True` if the field name is valid, else `False`.
  334. """
  335. return field_name not in FIELD_MAPPING and \
  336. not field_name.startswith(('metric/', 'user_defined/'))
  337. def _handle_limit_and_offset(self, condition, result):
  338. """
  339. Handling the condition of `limit` and `offset`.
  340. Args:
  341. condition (dict): Filter and sort condition.
  342. result (list[SuperLineageObj]): Filtered and sorted result.
  343. Returns:
  344. list[SuperLineageObj], paginated result.
  345. """
  346. offset = 0
  347. limit = 10
  348. if ConditionParam.OFFSET.value in condition:
  349. offset = condition.get(ConditionParam.OFFSET.value)
  350. if ConditionParam.LIMIT.value in condition:
  351. limit = condition.get(ConditionParam.LIMIT.value)
  352. if ConditionParam.OFFSET.value not in condition \
  353. and ConditionParam.LIMIT.value not in condition:
  354. offset_result = result
  355. else:
  356. offset_result = result[offset * limit: limit * (offset + 1)]
  357. return offset_result
  358. def _add_dataset_mark(self):
  359. """Add dataset mark into LineageObj."""
  360. # give a dataset mark for each dataset graph in lineage information
  361. marked_dataset_group = {'1': None}
  362. for super_lineage_obj in self._super_lineage_objs.values():
  363. lineage = super_lineage_obj.lineage_obj
  364. dataset_mark = '0'
  365. for dataset_graph_mark, marked_dataset_graph in marked_dataset_group.items():
  366. if marked_dataset_graph == lineage.dataset_graph:
  367. dataset_mark = dataset_graph_mark
  368. break
  369. # if no matched, add the new dataset graph into group
  370. if dataset_mark == '0':
  371. dataset_mark = str(int(max(marked_dataset_group.keys())) + 1)
  372. marked_dataset_group.update({
  373. dataset_mark:
  374. lineage.dataset_graph
  375. })
  376. lineage.dataset_mark = dataset_mark

MindInsight为MindSpore提供了简单易用的调优调试能力。在训练过程中,可以将标量、张量、图像、计算图、模型超参、训练耗时等数据记录到文件中,通过MindInsight可视化页面进行查看及分析。