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.

model.py 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # Copyright 2019 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 the model lineage python api."""
  16. import os
  17. from mindinsight.lineagemgr.common.exceptions.exceptions import LineageParamValueError, \
  18. LineageFileNotFoundError, LineageQuerySummaryDataError, LineageParamSummaryPathError, \
  19. LineageQuerierParamException, LineageDirNotExistError, LineageSearchConditionParamError, \
  20. LineageParamTypeError, LineageSummaryParseException
  21. from mindinsight.lineagemgr.common.log import logger as log
  22. from mindinsight.lineagemgr.common.path_parser import SummaryPathParser
  23. from mindinsight.lineagemgr.common.validator.model_parameter import SearchModelConditionParameter
  24. from mindinsight.lineagemgr.common.validator.validate import validate_filter_key
  25. from mindinsight.lineagemgr.common.validator.validate import validate_search_model_condition, \
  26. validate_condition, validate_path
  27. from mindinsight.lineagemgr.querier.querier import Querier
  28. from mindinsight.utils.exceptions import MindInsightException
  29. def get_summary_lineage(summary_dir, keys=None):
  30. """
  31. Get the lineage information according to summary directory and keys.
  32. The function queries lineage information of single train process
  33. corresponding to the given summary directory. Users can query the
  34. information according to `keys`.
  35. Args:
  36. summary_dir (str): The summary directory. It contains summary logs for
  37. one training.
  38. keys (list[str]): The filter keys of lineage information. The acceptable
  39. keys are `metric`, `user_defined`, `hyper_parameters`, `algorithm`,
  40. `train_dataset`, `model`, `valid_dataset` and `dataset_graph`.
  41. If it is `None`, all information will be returned. Default: None.
  42. Returns:
  43. dict, the lineage information for one training.
  44. Raises:
  45. LineageParamSummaryPathError: If summary path is invalid.
  46. LineageQuerySummaryDataError: If querying summary data fails.
  47. LineageFileNotFoundError: If the summary log file is not found.
  48. Examples:
  49. >>> summary_dir = "/path/to/summary"
  50. >>> summary_lineage_info = get_summary_lineage(summary_dir)
  51. >>> hyper_parameters = get_summary_lineage(summary_dir, keys=["hyper_parameters"])
  52. """
  53. try:
  54. summary_dir = validate_path(summary_dir)
  55. except MindInsightException as error:
  56. log.error(str(error))
  57. log.exception(error)
  58. raise LineageParamSummaryPathError(str(error.message))
  59. if keys is not None:
  60. validate_filter_key(keys)
  61. summary_path = SummaryPathParser.get_latest_lineage_summary(summary_dir)
  62. if summary_path is None:
  63. log.error('There is no summary log file under summary_dir.')
  64. raise LineageFileNotFoundError(
  65. 'There is no summary log file under summary_dir.'
  66. )
  67. try:
  68. result = Querier(summary_path).get_summary_lineage(
  69. summary_dir, filter_keys=keys)
  70. except LineageSummaryParseException:
  71. return {}
  72. except (LineageQuerierParamException, LineageParamTypeError) as error:
  73. log.error(str(error))
  74. log.exception(error)
  75. raise LineageQuerySummaryDataError("Get summary lineage failed.")
  76. return result[0]
  77. def filter_summary_lineage(summary_base_dir, search_condition=None):
  78. """
  79. Filter the lineage information under summary base directory according to search condition.
  80. Users can filter and sort all lineage information according to the search
  81. condition. The supported filter fields include `summary_dir`, `network`,
  82. etc. The filter conditions include `eq`, `lt`, `gt`, `le`, `ge` and `in`.
  83. If the value type of filter condition is `str`, such as summary_dir and
  84. lineage_type, then its key can only be `in` and `eq`. At the same time,
  85. the combined use of these fields and conditions is supported. If you want
  86. to sort based on filter fields, the field of `sorted_name` and `sorted_type`
  87. should be specified.
  88. Users can use `lineage_type` to decide what kind of lineage information to
  89. query. If the `lineage_type` is not defined, the query result is all lineage
  90. information.
  91. Users can paginate query result based on `offset` and `limit`. The `offset`
  92. refers to page number. The `limit` refers to the number in one page.
  93. Args:
  94. summary_base_dir (str): The summary base directory. It contains summary
  95. directories generated by training.
  96. search_condition (dict): The search condition. When filtering and
  97. sorting, in addition to the following supported fields, fields
  98. prefixed with `metric/` and `user_defined/` are also supported.
  99. For example, the field should be `metric/accuracy` if the key
  100. of `metrics` parameter is `accuracy`. The fields prefixed with
  101. `metric/` and `user_defined/` are related to the `metrics`
  102. parameter in the training script and user defined information in
  103. TrainLineage/EvalLineage callback, respectively. Default: None.
  104. - summary_dir (dict): The filter condition of summary directory.
  105. - loss_function (dict): The filter condition of loss function.
  106. - train_dataset_path (dict): The filter condition of train dataset path.
  107. - train_dataset_count (dict): The filter condition of train dataset count.
  108. - test_dataset_path (dict): The filter condition of test dataset path.
  109. - test_dataset_count (dict): The filter condition of test dataset count.
  110. - network (dict): The filter condition of network.
  111. - optimizer (dict): The filter condition of optimizer.
  112. - learning_rate (dict): The filter condition of learning rate.
  113. - epoch (dict): The filter condition of epoch.
  114. - batch_size (dict): The filter condition of batch size.
  115. - loss (dict): The filter condition of loss.
  116. - model_size (dict): The filter condition of model size.
  117. - dataset_mark (dict): The filter condition of dataset mark.
  118. - lineage_type (dict): The filter condition of lineage type. It decides
  119. what kind of lineage information to query. Its value can be `dataset`
  120. or `model`, e.g., {'in': ['dataset', 'model']}, {'eq': 'model'}, etc.
  121. If its values contain `dataset`, the query result will contain the
  122. lineage information related to data augmentation. If its values contain
  123. `model`, the query result will contain model lineage information.
  124. If it is not defined or it is a dict like {'in': ['dataset', 'model']},
  125. the query result is all lineage information.
  126. - offset (int): Page number, the value range is [0, 100000].
  127. - limit (int): The number in one page, the value range is [1, 100].
  128. - sorted_name (str): Specify which field to sort by.
  129. - sorted_type (str): Specify sort order. It can be `ascending` or
  130. `descending`.
  131. Returns:
  132. dict, lineage information under summary base directory according to
  133. search condition.
  134. Raises:
  135. LineageSearchConditionParamError: If search_condition param is invalid.
  136. LineageParamSummaryPathError: If summary path is invalid.
  137. LineageFileNotFoundError: If the summary log file is not found.
  138. LineageQuerySummaryDataError: If querying summary log file data fails.
  139. Examples:
  140. >>> summary_base_dir = "/path/to/summary_base"
  141. >>> search_condition = {
  142. >>> 'summary_dir': {
  143. >>> 'in': [
  144. >>> os.path.join(summary_base_dir, 'summary_1'),
  145. >>> os.path.join(summary_base_dir, 'summary_2'),
  146. >>> os.path.join(summary_base_dir, 'summary_3')
  147. >>> ]
  148. >>> },
  149. >>> 'loss': {
  150. >>> 'gt': 2.0
  151. >>> },
  152. >>> 'batch_size': {
  153. >>> 'ge': 128,
  154. >>> 'le': 256
  155. >>> },
  156. >>> 'metric/accuracy': {
  157. >>> 'lt': 0.1
  158. >>> },
  159. >>> 'sorted_name': 'summary_dir',
  160. >>> 'sorted_type': 'descending',
  161. >>> 'limit': 3,
  162. >>> 'offset': 0,
  163. >>> 'lineage_type': {
  164. >>> 'eq': 'model'
  165. >>> }
  166. >>> }
  167. >>> summary_lineage = filter_summary_lineage(summary_base_dir)
  168. >>> summary_lineage_filter = filter_summary_lineage(summary_base_dir, search_condition)
  169. """
  170. try:
  171. summary_base_dir = validate_path(summary_base_dir)
  172. except (LineageParamValueError, LineageDirNotExistError) as error:
  173. log.error(str(error))
  174. log.exception(error)
  175. raise LineageParamSummaryPathError(str(error.message))
  176. search_condition = {} if search_condition is None else search_condition
  177. try:
  178. validate_condition(search_condition)
  179. validate_search_model_condition(SearchModelConditionParameter, search_condition)
  180. except MindInsightException as error:
  181. log.error(str(error))
  182. log.exception(error)
  183. raise LineageSearchConditionParamError(str(error.message))
  184. try:
  185. search_condition = _convert_relative_path_to_abspath(summary_base_dir, search_condition)
  186. except (LineageParamValueError, LineageDirNotExistError) as error:
  187. log.error(str(error))
  188. log.exception(error)
  189. raise LineageParamSummaryPathError(str(error.message))
  190. summary_path = SummaryPathParser.get_latest_lineage_summaries(summary_base_dir)
  191. if not summary_path:
  192. log.error('There is no summary log file under summary_base_dir.')
  193. raise LineageFileNotFoundError(
  194. 'There is no summary log file under summary_base_dir.'
  195. )
  196. try:
  197. result = Querier(summary_path).filter_summary_lineage(
  198. condition=search_condition
  199. )
  200. except LineageSummaryParseException:
  201. result = {'object': [], 'count': 0}
  202. except (LineageQuerierParamException, LineageParamTypeError) as error:
  203. log.error(str(error))
  204. log.exception(error)
  205. raise LineageQuerySummaryDataError("Filter summary lineage failed.")
  206. return result
  207. def _convert_relative_path_to_abspath(summary_base_dir, search_condition):
  208. """
  209. Convert relative path to absolute path.
  210. Args:
  211. summary_base_dir (str): The summary base directory.
  212. search_condition (dict): The search condition.
  213. Returns:
  214. dict, the updated search_condition.
  215. Raises:
  216. LineageParamValueError: If the value of input_name is invalid.
  217. """
  218. if ("summary_dir" not in search_condition) or (not search_condition.get("summary_dir")):
  219. return search_condition
  220. summary_dir_condition = search_condition.get("summary_dir")
  221. if 'in' in summary_dir_condition:
  222. summary_paths = []
  223. for summary_dir in summary_dir_condition.get('in'):
  224. if summary_dir.startswith('./'):
  225. abs_dir = os.path.join(
  226. summary_base_dir, summary_dir[2:]
  227. )
  228. abs_dir = validate_path(abs_dir)
  229. else:
  230. abs_dir = validate_path(summary_dir)
  231. summary_paths.append(abs_dir)
  232. search_condition.get('summary_dir')['in'] = summary_paths
  233. if 'eq' in summary_dir_condition:
  234. summary_dir = summary_dir_condition.get('eq')
  235. if summary_dir.startswith('./'):
  236. abs_dir = os.path.join(
  237. summary_base_dir, summary_dir[2:]
  238. )
  239. abs_dir = validate_path(abs_dir)
  240. else:
  241. abs_dir = validate_path(summary_dir)
  242. search_condition.get('summary_dir')['eq'] = abs_dir
  243. return search_condition

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