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.

_summary_collector.py 40 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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. """Summary collector callback."""
  16. import os
  17. import re
  18. import json
  19. from json.decoder import JSONDecodeError
  20. from importlib import import_module
  21. import numpy as np
  22. from mindspore import log as logger
  23. from mindspore.common.tensor import Tensor
  24. from mindspore.common.parameter import Parameter
  25. from mindspore.train.summary.summary_record import SummaryRecord
  26. from mindspore.train.summary.enums import PluginEnum, ModeEnum
  27. from mindspore.train.callback import Callback, ModelCheckpoint
  28. from mindspore.train import lineage_pb2
  29. from mindspore.train.callback._dataset_graph import DatasetGraph
  30. from mindspore.nn.optim.optimizer import Optimizer
  31. from mindspore.nn.loss.loss import _Loss
  32. from mindspore.train._utils import check_value_type
  33. HYPER_CONFIG_ENV_NAME = "MINDINSIGHT_HYPER_CONFIG"
  34. HYPER_CONFIG_LEN_LIMIT = 100000
  35. class LineageMetadata:
  36. """Initialize parameters used in model lineage management."""
  37. train_dataset_path = 'train_dataset_path'
  38. valid_dataset_path = 'valid_dataset_path'
  39. train_network = 'train_network'
  40. loss_function = 'loss_function'
  41. loss = 'loss'
  42. optimizer = 'optimizer'
  43. learning_rate = 'learning_rate'
  44. epoch = 'epoch'
  45. step_num = 'step_num'
  46. parallel_mode = 'parallel_mode'
  47. device_num = 'device_num'
  48. batch_size = 'batch_size'
  49. model_path = 'model_path'
  50. model_ckpt = 'model_ckpt'
  51. model_size = 'model_size'
  52. metrics = 'metrics'
  53. train_dataset_size = 'train_dataset_size'
  54. valid_dataset_size = 'valid_dataset_size'
  55. class SummaryCollector(Callback):
  56. """
  57. SummaryCollector can help you to collect some common information.
  58. It can help you to collect loss, learning late, computational graph and so on.
  59. SummaryCollector also enables the summary operator to collect data from a summary file.
  60. Note:
  61. 1. Multiple SummaryCollector instances in callback list are not allowed.
  62. 2. Not all information is collected at the training phase or at the eval phase.
  63. 3. SummaryCollector always record the data collected by the summary operator.
  64. 4. SummaryCollector only supports Linux systems.
  65. Args:
  66. summary_dir (str): The collected data will be persisted to this directory.
  67. If the directory does not exist, it will be created automatically.
  68. collect_freq (int): Set the frequency of data collection, it should be greater then zero,
  69. and the unit is `step`. Default: 10. If a frequency is set, we will collect data
  70. when (current steps % freq) equals to 0, and the first step will be collected at any time.
  71. It is important to note that if the data sink mode is used, the unit will become the `epoch`.
  72. It is not recommended to collect data too frequently, which can affect performance.
  73. collect_specified_data (Union[None, dict]): Perform custom operations on the collected data. Default: None.
  74. By default, if set to None, all data is collected as the default behavior.
  75. You can customize the collected data with a dictionary.
  76. For example, you can set {'collect_metric': False} to control not collecting metrics.
  77. The data that supports control is shown below.
  78. - collect_metric: Whether to collect training metrics, currently only the loss is collected.
  79. The first output will be treated as the loss and it will be averaged.
  80. Optional: True/False. Default: True.
  81. - collect_graph: Whether to collect the computational graph. Currently, only
  82. training computational graph is collected. Optional: True/False. Default: True.
  83. - collect_train_lineage: Whether to collect lineage data for the training phase,
  84. this field will be displayed on the lineage page of Mindinsight. Optional: True/False. Default: True.
  85. - collect_eval_lineage: Whether to collect lineage data for the evaluation phase,
  86. this field will be displayed on the lineage page of Mindinsight. Optional: True/False. Default: True.
  87. - collect_input_data: Whether to collect dataset for each training. Currently only image data is supported.
  88. Optional: True/False. Default: True.
  89. - collect_dataset_graph: Whether to collect dataset graph for the training phase.
  90. Optional: True/False. Default: True.
  91. - histogram_regular: Collect weight and bias for parameter distribution page and displayed in MindInsight.
  92. This field allows regular strings to control which parameters to collect.
  93. Default: None, it means only the first five parameters are collected.
  94. It is not recommended to collect too many parameters at once, as it can affect performance.
  95. Note that if you collect too many parameters and run out of memory, the training will fail.
  96. keep_default_action (bool): This field affects the collection behavior of the 'collect_specified_data' field.
  97. Optional: True/False, Default: True.
  98. True: it means that after specified data is set, non-specified data is collected as the default behavior.
  99. False: it means that after specified data is set, only the specified data is collected,
  100. and the others are not collected.
  101. custom_lineage_data (Union[dict, None]): Allows you to customize the data and present it on the MingInsight
  102. lineage page. In the custom data, the type of the key supports str, and the type of value supports str, int
  103. and float. Default: None, it means there is no custom data.
  104. collect_tensor_freq (Optional[int]): The same semantics as the `collect_freq`, but controls TensorSummary only.
  105. Because TensorSummary data is too large to be compared with other summary data, this parameter is used to
  106. reduce its collection. By default, The maximum number of steps for collecting TensorSummary data is 20,
  107. but it will not exceed the number of steps for collecting other summary data.
  108. Default: None, which means to follow the behavior as described above. For example, given `collect_freq=10`,
  109. when the total steps is 600, TensorSummary will be collected 20 steps, while other summary data 61 steps,
  110. but when the total steps is 20, both TensorSummary and other summary will be collected 3 steps.
  111. Also note that when in parallel mode, the total steps will be splitted evenly, which will
  112. affect the number of steps TensorSummary will be collected.
  113. max_file_size (Optional[int]): The maximum size in bytes of each file that can be written to the disk.
  114. Default: None, which means no limit. For example, to write not larger than 4GB,
  115. specify `max_file_size=4 * 1024**3`.
  116. Raises:
  117. ValueError: If the parameter value is not expected.
  118. TypeError: If the parameter type is not expected.
  119. RuntimeError: If an error occurs during data collection.
  120. Examples:
  121. >>> # Simple usage:
  122. >>> summary_collector = SummaryCollector(summary_dir='./summary_dir')
  123. >>> model.train(epoch, dataset, callbacks=summary_collector)
  124. >>>
  125. >>> # Do not collect metric and collect the first layer parameter, others are collected by default
  126. >>> specified={'collect_metric': False, 'histogram_regular': '^conv1.*'}
  127. >>> summary_collector = SummaryCollector(summary_dir='./summary_dir', collect_specified_data=specified)
  128. >>> model.train(epoch, dataset, callbacks=summary_collector)
  129. >>>
  130. >>> # Only collect metric, custom lineage data and record data that collected by the summary operator,
  131. >>> # others are not collected
  132. >>> specified = {'collect_metric': True}
  133. >>> summary_collector = SummaryCollector('./summary_dir',
  134. >>> collect_specified_data=specified,
  135. >>> keep_default_action=False,
  136. >>> custom_lineage_data={'version': 'resnet50_v1'}
  137. >>> )
  138. >>> model.train(epoch, dataset, callbacks=summary_collector)
  139. """
  140. _DEFAULT_SPECIFIED_DATA = {
  141. 'collect_metric': True,
  142. 'collect_graph': True,
  143. 'collect_train_lineage': True,
  144. 'collect_eval_lineage': True,
  145. 'collect_input_data': True,
  146. 'collect_dataset_graph': True,
  147. 'histogram_regular': None
  148. }
  149. def __init__(self,
  150. summary_dir,
  151. collect_freq=10,
  152. collect_specified_data=None,
  153. keep_default_action=True,
  154. custom_lineage_data=None,
  155. collect_tensor_freq=None,
  156. max_file_size=None):
  157. super(SummaryCollector, self).__init__()
  158. self._summary_dir = self._process_summary_dir(summary_dir)
  159. self._record = None
  160. self._check_positive('collect_freq', collect_freq)
  161. self._collect_freq = collect_freq
  162. self._check_positive('collect_tensor_freq', collect_tensor_freq, allow_none=True)
  163. self._collect_tensor_freq = collect_tensor_freq
  164. self._tensor_collect_range = None
  165. self._check_positive('max_file_size', max_file_size, allow_none=True)
  166. self._max_file_size = max_file_size
  167. self._check_action(keep_default_action)
  168. self._collect_specified_data = self._process_specified_data(collect_specified_data, keep_default_action)
  169. msg = f"For 'collect_specified_data' the value after processing is: {self._collect_specified_data}."
  170. logger.info(msg)
  171. self._custom_lineage_data = self._process_custom_lineage_data(custom_lineage_data)
  172. self._temp_optimizer = None
  173. self._has_saved_graph = False
  174. self._has_saved_custom_data = False
  175. self._is_parse_loss_success = True
  176. self._first_step = True
  177. self._dataset_sink_mode = True
  178. def __enter__(self):
  179. self._record = SummaryRecord(log_dir=self._summary_dir, max_file_size=self._max_file_size)
  180. self._first_step, self._dataset_sink_mode = True, True
  181. return self
  182. def __exit__(self, *err):
  183. self._record.close()
  184. @staticmethod
  185. def _process_summary_dir(summary_dir):
  186. """Check the summary dir, and create a new directory if it not exists."""
  187. check_value_type('summary_dir', summary_dir, str)
  188. summary_dir = summary_dir.strip()
  189. if not summary_dir:
  190. raise ValueError('For `summary_dir` the value should be a valid string of path, but got empty string.')
  191. summary_dir = os.path.realpath(summary_dir)
  192. if not os.path.exists(summary_dir):
  193. os.makedirs(summary_dir, exist_ok=True)
  194. else:
  195. if not os.path.isdir(summary_dir):
  196. raise NotADirectoryError('For `summary_dir` it should be a directory path.')
  197. return summary_dir
  198. @staticmethod
  199. def _check_positive(name, value, allow_none=False):
  200. """Check if the value to be int type and positive."""
  201. if allow_none and value is None:
  202. return
  203. check_value_type(name, value, int)
  204. if value <= 0:
  205. raise ValueError(f'For `{name}` the value should be greater than 0, but got `{value}`.')
  206. def _process_custom_lineage_data(self, custom_lineage_data):
  207. """
  208. Check user custom lineage data.
  209. Args:
  210. custom_lineage_data (dict): The user custom defined data.
  211. Raises:
  212. TypeError: If the type of parameters is invalid.
  213. """
  214. if custom_lineage_data is None:
  215. custom_lineage_data = {}
  216. self._check_custom_lineage_type('custom_lineage_data', custom_lineage_data)
  217. auto_custom_lineage_data = self._collect_optimizer_custom_lineage_data()
  218. self._check_custom_lineage_type('auto_custom_lineage_data', auto_custom_lineage_data)
  219. # the priority of user defined info is higher than auto collected info
  220. auto_custom_lineage_data.update(custom_lineage_data)
  221. custom_lineage_data = auto_custom_lineage_data
  222. return custom_lineage_data
  223. def _check_custom_lineage_type(self, param_name, custom_lineage):
  224. """Check custom lineage type."""
  225. check_value_type(param_name, custom_lineage, [dict, type(None)])
  226. for key, value in custom_lineage.items():
  227. check_value_type(f'{param_name} -> {key}', key, str)
  228. check_value_type(f'the value of {param_name} -> {key}', value, (int, str, float))
  229. def _collect_optimizer_custom_lineage_data(self):
  230. """Collect custom lineage data if mindoptimizer has set the hyper config"""
  231. auto_custom_lineage_data = {}
  232. hyper_config = os.environ.get(HYPER_CONFIG_ENV_NAME)
  233. if hyper_config is None:
  234. logger.debug("Hyper config is not in system environment.")
  235. return auto_custom_lineage_data
  236. if len(hyper_config) > HYPER_CONFIG_LEN_LIMIT:
  237. logger.warning("Hyper config is too long. The length limit is %s, the length of "
  238. "hyper_config is %s." % (HYPER_CONFIG_LEN_LIMIT, len(hyper_config)))
  239. return auto_custom_lineage_data
  240. try:
  241. hyper_config = json.loads(hyper_config)
  242. except (TypeError, JSONDecodeError) as exc:
  243. logger.warning("Hyper config decode error. Detail: %s." % str(exc))
  244. return auto_custom_lineage_data
  245. custom_lineage_data = hyper_config.get("custom_lineage_data")
  246. if custom_lineage_data is None:
  247. logger.info("No custom lineage data in hyper config. Please check the custom lineage data "
  248. "if custom parameters exist in the configuration file.")
  249. auto_custom_lineage_data = custom_lineage_data if custom_lineage_data is not None else {}
  250. return auto_custom_lineage_data
  251. @staticmethod
  252. def _check_action(action):
  253. """Check action type."""
  254. check_value_type('keep_default_action', action, bool)
  255. def _process_specified_data(self, specified_data, action):
  256. """Check specified data type and value."""
  257. if specified_data is None:
  258. if action:
  259. return dict(self._DEFAULT_SPECIFIED_DATA)
  260. return dict()
  261. check_value_type('collect_specified_data', specified_data, [dict, type(None)])
  262. for param_name in specified_data:
  263. check_value_type(param_name, param_name, [str])
  264. unexpected_params = set(specified_data) - set(self._DEFAULT_SPECIFIED_DATA)
  265. if unexpected_params:
  266. raise ValueError(f'For `collect_specified_data` the keys {unexpected_params} are unsupported, '
  267. f'expect the follow keys: {list(self._DEFAULT_SPECIFIED_DATA.keys())}')
  268. if 'histogram_regular' in specified_data:
  269. check_value_type('histogram_regular', specified_data.get('histogram_regular'), (str, type(None)))
  270. bool_items = set(self._DEFAULT_SPECIFIED_DATA) - {'histogram_regular'}
  271. for item in bool_items:
  272. if item in specified_data:
  273. check_value_type(item, specified_data.get(item), bool)
  274. if action:
  275. result = dict(self._DEFAULT_SPECIFIED_DATA)
  276. result.update(specified_data)
  277. else:
  278. result = specified_data
  279. return result
  280. def begin(self, run_context):
  281. cb_params = run_context.original_args()
  282. self._check_callbacks(cb_params)
  283. if cb_params.mode not in ModeEnum.to_list():
  284. raise ValueError('Only support `train` (model.train) and `eval` (model.eval) mode, '
  285. 'but got `{cb_params.mode}` mode.')
  286. self._record.set_mode(cb_params.mode)
  287. def step_end(self, run_context):
  288. cb_params = run_context.original_args()
  289. if cb_params.mode != ModeEnum.TRAIN.value:
  290. return
  291. if not self._has_saved_graph:
  292. self._collect_graphs(cb_params)
  293. self._collect_dataset_graph(cb_params)
  294. self._has_saved_graph = True
  295. self._record.record(cb_params.cur_step_num)
  296. if self._custom_lineage_data and not self._has_saved_custom_data:
  297. packaged_custom_data = self._package_custom_lineage_data(self._custom_lineage_data)
  298. self._record.add_value('custom_lineage_data', 'custom_lineage_data', packaged_custom_data)
  299. self._has_saved_custom_data = True
  300. self._record.record(cb_params.cur_step_num)
  301. if self._first_step:
  302. # Notice: This way of determining whether dataset sink mode is True does not work in the eval scenario
  303. self._dataset_sink_mode = cb_params.cur_step_num == cb_params.batch_num
  304. self._tensor_collect_range = self._get_tensor_collect_range(cb_params, self._dataset_sink_mode)
  305. self._collect_at_step_end(cb_params, plugin_filter=None)
  306. self._first_step = False
  307. self._record.flush()
  308. else:
  309. current = cb_params.cur_epoch_num if self._dataset_sink_mode else cb_params.cur_step_num
  310. if current % self._collect_freq == 0 and current in self._tensor_collect_range:
  311. self._collect_at_step_end(cb_params, plugin_filter=None)
  312. elif current in self._tensor_collect_range:
  313. self._collect_at_step_end(cb_params, lambda plugin: plugin == PluginEnum.TENSOR.value)
  314. elif current % self._collect_freq == 0:
  315. self._collect_at_step_end(cb_params, lambda plugin: plugin != PluginEnum.TENSOR.value)
  316. def _get_tensor_collect_range(self, cb_params, dataset_sink_mode):
  317. """Get tensor collect range."""
  318. total_step = cb_params.epoch_num
  319. if not dataset_sink_mode:
  320. total_step *= cb_params.batch_num
  321. if self._collect_tensor_freq is not None:
  322. # `total_step + 1`: `total_step` would be a value of `cb_params.cur_step_num`.
  323. return range(0, total_step + 1, self._collect_tensor_freq)
  324. summary_to_collect = len(range(0, total_step + 1, self._collect_freq))
  325. default_tensor_summary_limit = 20
  326. if summary_to_collect > default_tensor_summary_limit:
  327. tensor_freq = total_step // (default_tensor_summary_limit - 1)
  328. if tensor_freq > 1:
  329. return range(0, total_step + 1, tensor_freq)[:default_tensor_summary_limit]
  330. # `cb_params.cur_step_num` counting from `1`, when `1` is in the range, take `1` more steps.
  331. return range(0, total_step + 1)[:default_tensor_summary_limit + 1]
  332. return range(0, total_step + 1, self._collect_freq)
  333. def _collect_at_step_end(self, cb_params, plugin_filter):
  334. self._collect_input_data(cb_params)
  335. self._collect_metric(cb_params)
  336. self._collect_histogram(cb_params)
  337. self._record.record(cb_params.cur_step_num, plugin_filter=plugin_filter)
  338. def epoch_end(self, run_context):
  339. self._record.flush()
  340. def end(self, run_context):
  341. cb_params = run_context.original_args()
  342. if cb_params.mode == ModeEnum.TRAIN.value:
  343. self._collect_train_lineage(cb_params)
  344. else:
  345. self._collect_eval_lineage(cb_params)
  346. # This is a workaround to avoid record '_summary_tensor_cache'.
  347. self._record.set_mode('eval')
  348. # There's nothing special about setting step to 0 here, just to satisfy the interface call
  349. self._record.record(step=0)
  350. def _check_callbacks(self, cb_params):
  351. """Check there if there are duplicate instances of SummaryCollector."""
  352. callbacks = cb_params.list_callback
  353. is_find = False
  354. for callback in callbacks:
  355. if type(callback).__name__ == self.__class__.__name__:
  356. if not is_find:
  357. is_find = True
  358. continue
  359. raise ValueError(f"There are more than one {self.__class__.__name__} instance in callback list,"
  360. f"but expected only one {self.__class__.__name__} instance.")
  361. @staticmethod
  362. def _package_custom_lineage_data(custom_lineage_data):
  363. """
  364. Package user-defined lineage data into binary data.
  365. Args:
  366. custom_lineage_data (dict): User custom lineage data.
  367. Returns:
  368. UserDefinedInfo, a object of lineage_pb2.UserDefinedInfo.
  369. """
  370. user_defined_info = lineage_pb2.UserDefinedInfo()
  371. for key, value in custom_lineage_data.items():
  372. if isinstance(value, int):
  373. attr_name = "map_int32"
  374. elif isinstance(value, float):
  375. attr_name = "map_double"
  376. else:
  377. attr_name = "map_str"
  378. user_info = user_defined_info.user_info.add()
  379. getattr(user_info, attr_name)[key] = value
  380. return user_defined_info
  381. def _collect_input_data(self, cb_params):
  382. """Only support to collect image data."""
  383. if not self._collect_specified_data.get('collect_input_data'):
  384. return
  385. input_data = getattr(cb_params, 'train_dataset_element', None)
  386. if input_data is None:
  387. self._collect_specified_data['collect_input_data'] = False
  388. logger.info("The 'train_dataset_element' in cb_params is None, maybe there is dataset sink mode.")
  389. return
  390. if isinstance(input_data, (list, tuple)) and input_data:
  391. input_data = input_data[0]
  392. try:
  393. self._record.add_value(PluginEnum.IMAGE.value, 'input_data/auto', input_data)
  394. except (TypeError, ValueError):
  395. logger.warning('The input data of network are not image, so will not collect by SummaryCollector.')
  396. self._collect_specified_data['collect_input_data'] = False
  397. return
  398. def _collect_dataset_graph(self, cb_params):
  399. """Only collect train dataset graph."""
  400. if not self._collect_specified_data.get('collect_dataset_graph'):
  401. return
  402. # After analysis, we think that the validated dataset graph and the training dataset graph
  403. # should be consistent under normal scenarios, so only the training dataset graph is collected.
  404. if cb_params.mode == ModeEnum.TRAIN.value:
  405. train_dataset = cb_params.train_dataset
  406. dataset_graph = DatasetGraph()
  407. graph_bytes = dataset_graph.package_dataset_graph(train_dataset)
  408. self._record.add_value('dataset_graph', 'train_dataset', graph_bytes)
  409. def _collect_graphs(self, cb_params):
  410. """Collect the graph of train network and eval network."""
  411. if not self._collect_specified_data.get('collect_graph'):
  412. return
  413. network = cb_params.train_network if cb_params.mode == ModeEnum.TRAIN.value else cb_params.eval_network
  414. graph_proto = network.get_func_graph_proto()
  415. if graph_proto is None:
  416. return
  417. self._record.add_value(PluginEnum.GRAPH.value, 'train_network/auto', graph_proto)
  418. def _collect_metric(self, cb_params):
  419. """Collect metric, currently only collection Loss is supported."""
  420. if not self._collect_specified_data.get('collect_metric'):
  421. return
  422. loss = self._get_loss(cb_params)
  423. if loss is None:
  424. return
  425. try:
  426. self._record.add_value(PluginEnum.SCALAR.value, 'loss/auto', loss)
  427. except ValueError:
  428. logger.warning("The output of network is not a scalar, so will not collect loss in SummaryCollector.")
  429. self._collect_specified_data['collect_metric'] = False
  430. def _get_loss(self, cb_params):
  431. """
  432. Get loss from the network output.
  433. Args:
  434. cb_params (_InternalCallbackParam): Callback parameters.
  435. Returns:
  436. Union[Tensor, None], if parse loss success, will return a Tensor value(shape is [1]), else return None.
  437. """
  438. if not self._is_parse_loss_success:
  439. # If parsing has failed before, avoid repeating it
  440. return None
  441. output = cb_params.net_outputs
  442. if output is None:
  443. logger.warning("Can not find any output by this network, so will not collect loss in SummaryCollector.")
  444. self._is_parse_loss_success = False
  445. return None
  446. if isinstance(output, (int, float, Tensor)):
  447. loss = output
  448. elif isinstance(output, (list, tuple)) and output:
  449. # If the output is a list, since the default network returns loss first,
  450. # we assume that the first one is loss.
  451. loss = output[0]
  452. else:
  453. logger.warning("The output type could not be identified, so no loss was recorded in SummaryCollector.")
  454. self._is_parse_loss_success = False
  455. return None
  456. if not isinstance(loss, Tensor):
  457. loss = Tensor(loss)
  458. precision = 4
  459. loss = Tensor(round(np.mean(loss.asnumpy()), precision))
  460. return loss
  461. def _get_optimizer(self, cb_params):
  462. """
  463. Get optimizer from the cb_params or parse from the network.
  464. Args:
  465. cb_params (_InternalCallbackParam): Callback parameters.
  466. Returns:
  467. Union[Optimizer, None], if parse optimizer success, will return a optimizer, else return None.
  468. """
  469. # 'optimizer_failed' means find optimizer failed, so we will not collect data about optimizer.
  470. optimizer_failed = 'Failed'
  471. if self._temp_optimizer == optimizer_failed:
  472. return None
  473. if self._temp_optimizer is not None:
  474. return self._temp_optimizer
  475. optimizer = cb_params.optimizer
  476. if optimizer is None:
  477. network = cb_params.train_network if cb_params.mode == 'train' else cb_params.eval_network
  478. optimizer = self._parse_optimizer_by_network(network)
  479. if optimizer is None or not isinstance(optimizer, Optimizer):
  480. logger.warning("Can not find optimizer in network, or the optimizer does not inherit MindSpore's "
  481. "optimizer, so we will not collect data about optimizer in SummaryCollector.")
  482. optimizer = None
  483. self._temp_optimizer = optimizer if optimizer is not None else optimizer_failed
  484. return optimizer
  485. @staticmethod
  486. def _parse_optimizer_by_network(network):
  487. """Parse optimizer from network, if parse success will return a optimizer, else return None."""
  488. optimizer = None
  489. for _, cell in network.cells_and_names():
  490. if isinstance(cell, Optimizer):
  491. return cell
  492. try:
  493. optimizer = getattr(cell, 'optimizer')
  494. except AttributeError:
  495. continue
  496. if not isinstance(optimizer, Optimizer):
  497. continue
  498. # Optimizer found successfully
  499. break
  500. return optimizer
  501. def _collect_histogram(self, cb_params):
  502. """Collect histogram data, contain the parameter weight and bias."""
  503. # Note: if there is not a key named `histogram_regular` in `self._collect_specified_data`,
  504. # it means we will not collect histogram data.
  505. if 'histogram_regular' not in self._collect_specified_data:
  506. return
  507. optimizer = self._get_optimizer(cb_params)
  508. if optimizer is None:
  509. return
  510. parameters = optimizer.parameters
  511. regular = self._collect_specified_data.get('histogram_regular')
  512. if regular is not None:
  513. for parameter in parameters:
  514. if re.match(regular, parameter.name):
  515. self._record.add_value(PluginEnum.HISTOGRAM.value, parameter.name+'/auto', parameter.data)
  516. return
  517. # Note: If `histogram_regular` in `self._collect_specified_data` and the value is None,
  518. # we will collect the first five parameters.
  519. default_parameter_count = 5
  520. for parameter in parameters[:default_parameter_count]:
  521. self._record.add_value(PluginEnum.HISTOGRAM.value, parameter.name+'/auto', parameter.data)
  522. @staticmethod
  523. def _get_learning_rate(optimizer):
  524. """
  525. parse the learning rate from optimizer.
  526. Args:
  527. optimizer (Optimizer): A optimizer which inherit the MindSpore Optimizer class.
  528. Returns:
  529. Union[Tensor, None], if parse learning rate success, will return a Tensor, else return None.
  530. """
  531. learning_rate = optimizer.learning_rate
  532. if not isinstance(learning_rate, Parameter):
  533. logger.warning("The learning rate detected in the optimizer "
  534. "is not a Parameter type, so it is not recorded.")
  535. return None
  536. return learning_rate.data
  537. def _collect_train_lineage(self, cb_params):
  538. """Collect train lineage data, the detail refer to lineage_pb2.TrainLineage."""
  539. if not self._collect_specified_data.get('collect_train_lineage'):
  540. return
  541. train_lineage = {}
  542. loss = self._get_loss(cb_params)
  543. if loss is not None:
  544. loss_numpy = loss.asnumpy()
  545. loss = float(np.atleast_1d(loss_numpy)[0])
  546. train_lineage[LineageMetadata.loss] = loss
  547. else:
  548. train_lineage[LineageMetadata.loss] = None
  549. optimizer = self._get_optimizer(cb_params)
  550. learning_rate = self._get_learning_rate(optimizer) if optimizer is not None else None
  551. if learning_rate is not None:
  552. train_lineage[LineageMetadata.learning_rate] = list(np.atleast_1d(learning_rate.asnumpy()))[0]
  553. else:
  554. train_lineage[LineageMetadata.learning_rate] = None
  555. train_lineage[LineageMetadata.optimizer] = type(optimizer).__name__ if optimizer else None
  556. train_lineage[LineageMetadata.train_network] = type(cb_params.network).__name__
  557. loss_fn = self._get_loss_fn(cb_params)
  558. train_lineage[LineageMetadata.loss_function] = type(loss_fn).__name__ if loss_fn else None
  559. train_lineage[LineageMetadata.epoch] = cb_params.epoch_num
  560. train_lineage[LineageMetadata.step_num] = cb_params.cur_step_num
  561. train_lineage[LineageMetadata.parallel_mode] = cb_params.parallel_mode
  562. train_lineage[LineageMetadata.device_num] = cb_params.device_number
  563. ckpt_file_path = self._get_ckpt_file_path(cb_params)
  564. train_lineage[LineageMetadata.model_path] = json.dumps(dict(ckpt=ckpt_file_path))
  565. model_size = os.path.getsize(ckpt_file_path) if ckpt_file_path else 0
  566. train_lineage[LineageMetadata.model_size] = model_size
  567. self._parse_dataset(cb_params, train_lineage)
  568. train_lineage_message = self._package_train_lineage_message(train_lineage)
  569. self._record.add_value(PluginEnum.TRAIN_LINEAGE.value, 'train_lineage', train_lineage_message)
  570. @staticmethod
  571. def _package_train_lineage_message(train_lineage):
  572. """
  573. Package train lineage data into binary data.
  574. Args:
  575. train_lineage (dict): The train lineage dict, refer to the attribute of `_collect_train_lineage` method.
  576. Returns:
  577. TrainLineage, a object of lineage_pb2.TrainLineage.
  578. """
  579. lineage_message = lineage_pb2.TrainLineage()
  580. if train_lineage.get(LineageMetadata.train_network) is not None:
  581. lineage_message.algorithm.network = train_lineage.get(LineageMetadata.train_network)
  582. if train_lineage.get(LineageMetadata.loss) is not None:
  583. lineage_message.algorithm.loss = train_lineage.get(LineageMetadata.loss)
  584. # Construct train_dataset message.
  585. if train_lineage.get(LineageMetadata.train_dataset_path) is not None:
  586. lineage_message.train_dataset.train_dataset_path = train_lineage.get(LineageMetadata.train_dataset_path)
  587. if train_lineage.get(LineageMetadata.train_dataset_size) is not None:
  588. lineage_message.train_dataset.train_dataset_size = train_lineage.get(LineageMetadata.train_dataset_size)
  589. # Construct model message
  590. lineage_message.model.path = train_lineage.get(LineageMetadata.model_path)
  591. lineage_message.model.size = train_lineage.get(LineageMetadata.model_size)
  592. # Construct hyper_parameters message.
  593. if train_lineage.get(LineageMetadata.learning_rate) is not None:
  594. lineage_message.hyper_parameters.learning_rate = train_lineage.get(LineageMetadata.learning_rate)
  595. if train_lineage.get(LineageMetadata.optimizer) is not None:
  596. lineage_message.hyper_parameters.optimizer = train_lineage.get(LineageMetadata.optimizer)
  597. if train_lineage.get(LineageMetadata.loss_function) is not None:
  598. lineage_message.hyper_parameters.loss_function = train_lineage.get(LineageMetadata.loss_function)
  599. if train_lineage.get(LineageMetadata.parallel_mode) is not None:
  600. lineage_message.hyper_parameters.parallel_mode = train_lineage.get(LineageMetadata.parallel_mode)
  601. lineage_message.hyper_parameters.epoch = train_lineage.get(LineageMetadata.epoch)
  602. lineage_message.hyper_parameters.device_num = train_lineage.get(LineageMetadata.device_num)
  603. lineage_message.hyper_parameters.batch_size = train_lineage.get(LineageMetadata.batch_size)
  604. return lineage_message
  605. def _parse_dataset(self, cb_params, lineage_dict):
  606. """
  607. Analyze Dataset to get the dataset path and dataset size.
  608. Args:
  609. cb_params (_InternalCallbackParam): Callback parameters.
  610. lineage_dict (dict): The lineage dict, refer to the attribute
  611. of `_collect_train_lineage` method or `_collect_eval_lineage`.
  612. Returns:
  613. dict, the lineage metadata.
  614. """
  615. dataset = cb_params.train_dataset if cb_params.mode == ModeEnum.TRAIN.value else cb_params.valid_dataset
  616. try:
  617. dataset_path = self._get_dataset_path(dataset)
  618. except IndexError:
  619. dataset_path = None
  620. if dataset_path and os.path.isfile(dataset_path):
  621. dataset_dir = os.path.dirname(dataset_path)
  622. else:
  623. dataset_dir = dataset_path
  624. batch_num = dataset.get_dataset_size()
  625. batch_size = dataset.get_batch_size()
  626. dataset_size = int(batch_num * batch_size)
  627. lineage_dict[LineageMetadata.batch_size] = batch_size
  628. if cb_params.mode == ModeEnum.TRAIN.value:
  629. lineage_dict[LineageMetadata.train_dataset_path] = dataset_dir
  630. lineage_dict[LineageMetadata.train_dataset_size] = dataset_size
  631. else:
  632. lineage_dict[LineageMetadata.valid_dataset_path] = dataset_dir
  633. lineage_dict[LineageMetadata.valid_dataset_size] = dataset_size
  634. return lineage_dict
  635. def _get_dataset_path(self, output_dataset):
  636. """
  637. Get dataset path of MindDataset object.
  638. Args:
  639. output_dataset (Union[Dataset, ImageFolderDataset, MnistDataset, Cifar10Dataset, Cifar100Dataset,
  640. VOCDataset, CelebADataset, MindDataset, ManifestDataset, TFRecordDataset, TextFileDataset]):
  641. Refer to mindspore.dataset.Dataset.
  642. Returns:
  643. str, dataset path.
  644. Raises:
  645. IndexError: it means get dataset path failed.
  646. """
  647. dataset_package = import_module('mindspore.dataset')
  648. dataset_dir_set = (dataset_package.ImageFolderDataset, dataset_package.MnistDataset,
  649. dataset_package.Cifar10Dataset, dataset_package.Cifar100Dataset,
  650. dataset_package.VOCDataset, dataset_package.CelebADataset)
  651. dataset_file_set = (dataset_package.MindDataset, dataset_package.ManifestDataset)
  652. dataset_files_set = (dataset_package.TFRecordDataset, dataset_package.TextFileDataset)
  653. if isinstance(output_dataset, dataset_file_set):
  654. return output_dataset.dataset_file
  655. if isinstance(output_dataset, dataset_dir_set):
  656. return output_dataset.dataset_dir
  657. if isinstance(output_dataset, dataset_files_set):
  658. return output_dataset.dataset_files[0]
  659. return self._get_dataset_path(output_dataset.children[0])
  660. @staticmethod
  661. def _get_ckpt_file_path(cb_params):
  662. """
  663. Get checkpoint file path from MindSpore callback list.
  664. Args:
  665. cb_params (_InternalCallbackParam): Callback parameters.
  666. Returns:
  667. Union[str, None], if parse success will checkpoint file absolute path, else return None.
  668. """
  669. callbacks = cb_params.list_callback
  670. ckpt_file_path = None
  671. for callback in callbacks:
  672. if isinstance(callback, ModelCheckpoint):
  673. ckpt_file_path = callback.latest_ckpt_file_name
  674. if ckpt_file_path:
  675. ckpt_file_path = os.path.realpath(ckpt_file_path)
  676. return ckpt_file_path
  677. @staticmethod
  678. def _get_loss_fn(cb_params):
  679. """
  680. Get loss function by cb_params and analyzing network.
  681. Args:
  682. cb_params (_InternalCallbackParam): Callback parameters.
  683. Returns:
  684. Union[Cell, None], a Cell object, if parse failed, will return None.
  685. """
  686. loss_fn = cb_params.loss_fn
  687. if loss_fn is not None:
  688. return loss_fn
  689. if cb_params.mode == ModeEnum.TRAIN.value:
  690. network = cb_params.train_network
  691. else:
  692. network = cb_params.eval_network
  693. for _, cell in network.cells_and_names():
  694. if isinstance(cell, _Loss):
  695. loss_fn = cell
  696. break
  697. return loss_fn
  698. def _collect_eval_lineage(self, cb_params):
  699. """Collect eval lineage data, the detail refer to lineage_pb2.EvaluationLineage."""
  700. if not self._collect_specified_data.get('collect_eval_lineage'):
  701. return
  702. eval_lineage = dict()
  703. eval_lineage[LineageMetadata.metrics] = json.dumps(cb_params.metrics)
  704. self._parse_dataset(cb_params, eval_lineage)
  705. eval_lineage_message = self._package_eval_lineage_message(eval_lineage)
  706. self._record.add_value(PluginEnum.EVAL_LINEAGE.value, 'eval_lineage', eval_lineage_message)
  707. @staticmethod
  708. def _package_eval_lineage_message(eval_lineage):
  709. """
  710. Package eval lineage data into binary data.
  711. Args:
  712. eval_lineage (dict): The eval lineage dict, refer to the attribute of `_collect_eval_lineage` method.
  713. Returns:
  714. EvaluationLineage, a object of lineage_pb2.EvaluationLineage.
  715. """
  716. lineage_message = lineage_pb2.EvaluationLineage()
  717. if eval_lineage.get(LineageMetadata.metrics) is not None:
  718. lineage_message.metric = eval_lineage.get(LineageMetadata.metrics)
  719. if eval_lineage.get(LineageMetadata.valid_dataset_path) is not None:
  720. lineage_message.valid_dataset.valid_dataset_path = eval_lineage.get(LineageMetadata.valid_dataset_path)
  721. if eval_lineage.get(LineageMetadata.valid_dataset_size) is not None:
  722. lineage_message.valid_dataset.valid_dataset_size = eval_lineage.get(LineageMetadata.valid_dataset_size)
  723. return lineage_message