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.

events_data.py 7.8 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. """Takes a generator of values, and collects them for a frontend."""
  16. import collections
  17. import threading
  18. from mindinsight.datavisual.common.enums import PluginNameEnum
  19. from mindinsight.datavisual.data_transform import reservoir
  20. from mindinsight.conf import settings
  21. # Type of the tensor event from external component
  22. _Tensor = collections.namedtuple('_Tensor', ['wall_time', 'step', 'value'])
  23. TensorEvent = collections.namedtuple(
  24. 'TensorEvent', ['wall_time', 'step', 'tag', 'plugin_name', 'value'])
  25. # config for `EventsData`
  26. _DEFAULT_STEP_SIZES_PER_TAG = settings.DEFAULT_STEP_SIZES_PER_TAG
  27. CONFIG = {
  28. 'max_total_tag_sizes': settings.MAX_TAG_SIZE_PER_EVENTS_DATA,
  29. 'max_tag_sizes_per_plugin':
  30. {
  31. PluginNameEnum.GRAPH.value: settings.MAX_GRAPH_TAG_SIZE,
  32. },
  33. 'max_step_sizes_per_tag':
  34. {
  35. PluginNameEnum.SCALAR.value: settings.MAX_SCALAR_STEP_SIZE_PER_TAG,
  36. PluginNameEnum.IMAGE.value: settings.MAX_IMAGE_STEP_SIZE_PER_TAG,
  37. PluginNameEnum.GRAPH.value: settings.MAX_GRAPH_STEP_SIZE_PER_TAG,
  38. PluginNameEnum.HISTOGRAM.value: settings.MAX_HISTOGRAM_STEP_SIZE_PER_TAG
  39. }
  40. }
  41. class EventsData:
  42. """
  43. EventsData is an event data manager.
  44. It manages the log events generated during a training process.
  45. The log event records information such as graph, tag, and tensor.
  46. Data such as tensor can be retrieved based on its tag.
  47. """
  48. def __init__(self):
  49. self._config = CONFIG
  50. self._max_step_sizes_per_tag = self._config['max_step_sizes_per_tag']
  51. self._tags = list()
  52. self._reservoir_by_tag = {}
  53. self._reservoir_mutex_lock = threading.Lock()
  54. self._tags_by_plugin = collections.defaultdict(list)
  55. self._tags_by_plugin_mutex_lock = collections.defaultdict(threading.Lock)
  56. def add_tensor_event(self, tensor_event):
  57. """
  58. Add a new tensor event to the tensors_data.
  59. Args:
  60. tensor_event (TensorEvent): Refer to `TensorEvent` object.
  61. """
  62. if not isinstance(tensor_event, TensorEvent):
  63. raise TypeError('Expect to get data of type `TensorEvent`.')
  64. tag = tensor_event.tag
  65. plugin_name = tensor_event.plugin_name
  66. if tag not in set(self._tags):
  67. deleted_tag = self._check_tag_out_of_spec(plugin_name)
  68. if deleted_tag is not None:
  69. self.delete_tensor_event(deleted_tag)
  70. self._tags.append(tag)
  71. with self._tags_by_plugin_mutex_lock[plugin_name]:
  72. if tag not in self._tags_by_plugin[plugin_name]:
  73. self._tags_by_plugin[plugin_name].append(tag)
  74. with self._reservoir_mutex_lock:
  75. if tag not in self._reservoir_by_tag:
  76. reservoir_size = self._get_reservoir_size(tensor_event.plugin_name)
  77. self._reservoir_by_tag[tag] = reservoir.ReservoirFactory().create_reservoir(
  78. plugin_name, reservoir_size
  79. )
  80. tensor = _Tensor(wall_time=tensor_event.wall_time,
  81. step=tensor_event.step,
  82. value=tensor_event.value)
  83. if self._is_out_of_order_step(tensor_event.step, tensor_event.tag):
  84. self.purge_reservoir_data(tensor_event.step, self._reservoir_by_tag[tag])
  85. self._reservoir_by_tag[tag].add_sample(tensor)
  86. def delete_tensor_event(self, tag):
  87. """
  88. This function will delete tensor event by the given tag in memory record.
  89. Args:
  90. tag (str): The tag name.
  91. """
  92. self._tags.remove(tag)
  93. for plugin_name, lock in self._tags_by_plugin_mutex_lock.items():
  94. with lock:
  95. if tag in self._tags_by_plugin[plugin_name]:
  96. self._tags_by_plugin[plugin_name].remove(tag)
  97. break
  98. with self._reservoir_mutex_lock:
  99. if tag in self._reservoir_by_tag:
  100. self._reservoir_by_tag.pop(tag)
  101. def list_tags_by_plugin(self, plugin_name):
  102. """
  103. Return all the tag names of the plugin.
  104. Args:
  105. plugin_name (str): The Plugin name.
  106. Returns:
  107. list[str], tags of the plugin.
  108. Raises:
  109. KeyError: when plugin name could not be found.
  110. """
  111. if plugin_name not in self._tags_by_plugin:
  112. raise KeyError('Plugin %r could not be found.' % plugin_name)
  113. with self._tags_by_plugin_mutex_lock[plugin_name]:
  114. # Return a snapshot to avoid concurrent mutation and iteration issues.
  115. return list(self._tags_by_plugin[plugin_name])
  116. def tensors(self, tag):
  117. """
  118. Return all tensors of the tag.
  119. Args:
  120. tag (str): The tag name.
  121. Returns:
  122. list[_Tensor], the list of tensors to the tag.
  123. """
  124. if tag not in self._reservoir_by_tag:
  125. raise KeyError('TAG %r could not be found.' % tag)
  126. return self._reservoir_by_tag[tag].samples()
  127. def _is_out_of_order_step(self, step, tag):
  128. """
  129. If the current step is smaller than the latest one, it is out-of-order step.
  130. Args:
  131. step (int): Check if the given step out of order.
  132. tag (str): The checked tensor of the given tag.
  133. Returns:
  134. bool, boolean value.
  135. """
  136. if self.tensors(tag):
  137. tensors = self.tensors(tag)
  138. last_step = tensors[-1].step
  139. if step <= last_step:
  140. return True
  141. return False
  142. @staticmethod
  143. def purge_reservoir_data(start_step, tensor_reservoir):
  144. """
  145. Purge all tensor event that are out-of-order step after the given start step.
  146. Args:
  147. start_step (int): Urge start step. All previously seen events with
  148. a greater or equal to step will be purged.
  149. tensor_reservoir (Reservoir): A `Reservoir` object.
  150. Returns:
  151. int, the number of items removed.
  152. """
  153. cnt_out_of_order = tensor_reservoir.remove_sample(lambda x: x.step < start_step)
  154. return cnt_out_of_order
  155. def _get_reservoir_size(self, plugin_name):
  156. max_step_sizes_per_tag = self._config['max_step_sizes_per_tag']
  157. return max_step_sizes_per_tag.get(plugin_name, _DEFAULT_STEP_SIZES_PER_TAG)
  158. def _check_tag_out_of_spec(self, plugin_name):
  159. """
  160. Check whether the tag is out of specification.
  161. Args:
  162. plugin_name (str): The given plugin name.
  163. Returns:
  164. Union[str, None], if out of specification, will return the first tag, else return None.
  165. """
  166. tag_specifications = self._config['max_tag_sizes_per_plugin'].get(plugin_name)
  167. if tag_specifications is not None and len(self._tags_by_plugin[plugin_name]) >= tag_specifications:
  168. deleted_tag = self._tags_by_plugin[plugin_name][0]
  169. return deleted_tag
  170. if len(self._tags) >= self._config['max_total_tag_sizes']:
  171. deleted_tag = self._tags[0]
  172. return deleted_tag
  173. return None

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