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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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`, `hyper_parameters`, `algorithm`, `train_dataset`,
  40. `model`, `valid_dataset` and `dataset_graph`. If it is `None`, all
  41. 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. At the same time, the combined use of these fields and conditions is
  84. supported. If you want to sort based on filter fields, the field of
  85. `sorted_name` and `sorted_type` should be specified.
  86. Users can use `lineage_type` to decide what kind of lineage information to
  87. query. If the `lineage_type` is `dataset`, the query result is only the
  88. lineage information related to data augmentation. If the `lineage_type` is
  89. `model` or `None`, the query result is all lineage information.
  90. Users can paginate query result based on `offset` and `limit`. The `offset`
  91. refers to page number. The `limit` refers to the number in one page.
  92. Args:
  93. summary_base_dir (str): The summary base directory. It contains summary
  94. directories generated by training.
  95. search_condition (dict): The search condition. When filtering and
  96. sorting, in addition to the following supported fields, fields
  97. prefixed with `metric_` are also supported. The fields prefixed with
  98. `metric_` are related to the `metrics` parameter in the training
  99. script. For example, if the key of `metrics` parameter is
  100. `accuracy`, the field should be `metric_accuracy`. Default: None.
  101. - summary_dir (dict): The filter condition of summary directory.
  102. - loss_function (dict): The filter condition of loss function.
  103. - train_dataset_path (dict): The filter condition of train dataset path.
  104. - train_dataset_count (dict): The filter condition of train dataset count.
  105. - test_dataset_path (dict): The filter condition of test dataset path.
  106. - test_dataset_count (dict): The filter condition of test dataset count.
  107. - network (dict): The filter condition of network.
  108. - optimizer (dict): The filter condition of optimizer.
  109. - learning_rate (dict): The filter condition of learning rate.
  110. - epoch (dict): The filter condition of epoch.
  111. - batch_size (dict): The filter condition of batch size.
  112. - loss (dict): The filter condition of loss.
  113. - model_size (dict): The filter condition of model size.
  114. - dataset_mark (dict): The filter condition of dataset mark.
  115. - offset (int): Page number, the value range is [0, 100000].
  116. - limit (int): The number in one page, the value range is [1, 100].
  117. - sorted_name (str): Specify which field to sort by.
  118. - sorted_type (str): Specify sort order. It can be `ascending` or
  119. `descending`.
  120. - lineage_type (str): It decides what kind of lineage information to
  121. query. It can be `dataset` or `model`. If it is `dataset`,
  122. the query result is only the lineage information related to data
  123. augmentation. If it is `model` or `None`, the query result is all
  124. lineage information.
  125. Returns:
  126. dict, all lineage information under summary base directory according to
  127. search condition.
  128. Raises:
  129. LineageSearchConditionParamError: If search_condition param is invalid.
  130. LineageParamSummaryPathError: If summary path is invalid.
  131. LineageFileNotFoundError: If the summary log file is not found.
  132. LineageQuerySummaryDataError: If querying summary log file data fails.
  133. Examples:
  134. >>> summary_base_dir = "/path/to/summary_base"
  135. >>> search_condition = {
  136. >>> 'summary_dir': {
  137. >>> 'in': [
  138. >>> os.path.join(summary_base_dir, 'summary_1'),
  139. >>> os.path.join(summary_base_dir, 'summary_2'),
  140. >>> os.path.join(summary_base_dir, 'summary_3')
  141. >>> ]
  142. >>> },
  143. >>> 'loss': {
  144. >>> 'gt': 2.0
  145. >>> },
  146. >>> 'batch_size': {
  147. >>> 'ge': 128,
  148. >>> 'le': 256
  149. >>> },
  150. >>> 'metric_accuracy': {
  151. >>> 'lt': 0.1
  152. >>> },
  153. >>> 'sorted_name': 'summary_dir',
  154. >>> 'sorted_type': 'descending',
  155. >>> 'limit': 3,
  156. >>> 'offset': 0,
  157. >>> 'lineage_type': 'model'
  158. >>> }
  159. >>> summary_lineage = filter_summary_lineage(summary_base_dir)
  160. >>> summary_lineage_filter = filter_summary_lineage(summary_base_dir, search_condition)
  161. """
  162. try:
  163. summary_base_dir = validate_path(summary_base_dir)
  164. except (LineageParamValueError, LineageDirNotExistError) as error:
  165. log.error(str(error))
  166. log.exception(error)
  167. raise LineageParamSummaryPathError(str(error.message))
  168. search_condition = {} if search_condition is None else search_condition
  169. try:
  170. validate_condition(search_condition)
  171. validate_search_model_condition(SearchModelConditionParameter, search_condition)
  172. except MindInsightException as error:
  173. log.error(str(error))
  174. log.exception(error)
  175. raise LineageSearchConditionParamError(str(error.message))
  176. try:
  177. search_condition = _convert_relative_path_to_abspath(summary_base_dir, search_condition)
  178. except (LineageParamValueError, LineageDirNotExistError) as error:
  179. log.error(str(error))
  180. log.exception(error)
  181. raise LineageParamSummaryPathError(str(error.message))
  182. summary_path = SummaryPathParser.get_latest_lineage_summaries(summary_base_dir)
  183. if not summary_path:
  184. log.error('There is no summary log file under summary_base_dir.')
  185. raise LineageFileNotFoundError(
  186. 'There is no summary log file under summary_base_dir.'
  187. )
  188. try:
  189. result = Querier(summary_path).filter_summary_lineage(
  190. condition=search_condition
  191. )
  192. except LineageSummaryParseException:
  193. result = {'object': [], 'count': 0}
  194. except (LineageQuerierParamException, LineageParamTypeError) as error:
  195. log.error(str(error))
  196. log.exception(error)
  197. raise LineageQuerySummaryDataError("Filter summary lineage failed.")
  198. return result
  199. def _convert_relative_path_to_abspath(summary_base_dir, search_condition):
  200. """
  201. Convert relative path to absolute path.
  202. Args:
  203. summary_base_dir (str): The summary base directory.
  204. search_condition (dict): The search condition.
  205. Returns:
  206. dict, the updated search_condition.
  207. Raises:
  208. LineageParamValueError: If the value of input_name is invalid.
  209. """
  210. if ("summary_dir" not in search_condition) or (not search_condition.get("summary_dir")):
  211. return search_condition
  212. summary_dir_condition = search_condition.get("summary_dir")
  213. if not set(summary_dir_condition.keys()).issubset(['in', 'eq']):
  214. raise LineageParamValueError("Invalid operation of summary dir.")
  215. if 'in' in summary_dir_condition:
  216. summary_paths = []
  217. for summary_dir in summary_dir_condition.get('in'):
  218. if summary_dir.startswith('./'):
  219. abs_dir = os.path.join(
  220. summary_base_dir, summary_dir[2:]
  221. )
  222. abs_dir = validate_path(abs_dir)
  223. else:
  224. abs_dir = validate_path(summary_dir)
  225. summary_paths.append(abs_dir)
  226. search_condition.get('summary_dir')['in'] = summary_paths
  227. if 'eq' in summary_dir_condition:
  228. summary_dir = summary_dir_condition.get('eq')
  229. if summary_dir.startswith('./'):
  230. abs_dir = os.path.join(
  231. summary_base_dir, summary_dir[2:]
  232. )
  233. abs_dir = validate_path(abs_dir)
  234. else:
  235. abs_dir = validate_path(summary_dir)
  236. search_condition.get('summary_dir')['eq'] = abs_dir
  237. return search_condition

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

Contributors (1)