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