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.

explain_parser.py 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. """
  16. File parser for MindExplain data.
  17. This module is used to parse the MindExplain log file.
  18. """
  19. import re
  20. import collections
  21. from google.protobuf.message import DecodeError
  22. from mindinsight.datavisual.common import exceptions
  23. from mindinsight.explainer.common.enums import PluginNameEnum
  24. from mindinsight.explainer.common.log import logger
  25. from mindinsight.datavisual.data_access.file_handler import FileHandler
  26. from mindinsight.datavisual.data_transform.ms_data_loader import _SummaryParser
  27. from mindinsight.datavisual.proto_files import mindinsight_summary_pb2 as summary_pb2
  28. from mindinsight.utils.exceptions import UnknownError
  29. HEADER_SIZE = 8
  30. CRC_STR_SIZE = 4
  31. MAX_EVENT_STRING = 500000000
  32. ImageDataContainer = collections.namedtuple('ImageDataContainer',
  33. ['image_id', 'image_data', 'ground_truth_label',
  34. 'inference', 'explanation', 'status'])
  35. BenchmarkContainer = collections.namedtuple('BenchmarkContainer', ['benchmark', 'status'])
  36. MetadataContainer = collections.namedtuple('MetadataContainer', ['metadata', 'status'])
  37. class _ExplainParser(_SummaryParser):
  38. """The summary file parser."""
  39. def __init__(self, summary_dir):
  40. super(_ExplainParser, self).__init__(summary_dir)
  41. self._latest_filename = ''
  42. def parse_explain(self, filenames):
  43. """
  44. Load summary file and parse file content.
  45. Args:
  46. filenames (list[str]): File name list.
  47. Returns:
  48. bool, True if all the summary files are finished loading.
  49. """
  50. summary_files = self.filter_files(filenames)
  51. summary_files = self.sort_files(summary_files)
  52. is_end = False
  53. is_clean = False
  54. event_data = {}
  55. filename = summary_files[-1]
  56. file_path = FileHandler.join(self._summary_dir, filename)
  57. if filename != self._latest_filename:
  58. self._summary_file_handler = FileHandler(file_path, 'rb')
  59. self._latest_filename = filename
  60. self._latest_file_size = 0
  61. is_clean = True
  62. new_size = FileHandler.file_stat(file_path).size
  63. if new_size == self._latest_file_size:
  64. is_end = True
  65. return is_clean, is_end, event_data
  66. while True:
  67. start_offset = self._summary_file_handler.offset
  68. try:
  69. event_str = self._event_load(self._summary_file_handler)
  70. if event_str is None:
  71. self._summary_file_handler.reset_offset(start_offset)
  72. is_end = True
  73. return is_clean, is_end, event_data
  74. if len(event_str) > MAX_EVENT_STRING:
  75. logger.warning("file_path: %s, event string: %d exceeds %d and drop it.",
  76. self._summary_file_handler.file_path, len(event_str), MAX_EVENT_STRING)
  77. continue
  78. field_list, tensor_value_list = self._event_decode(event_str)
  79. for field, tensor_value in zip(field_list, tensor_value_list):
  80. event_data[field] = tensor_value
  81. logger.info("Parse summary file offset %d, file path: %s.", self._latest_file_size, file_path)
  82. return is_clean, is_end, event_data
  83. except exceptions.CRCFailedError:
  84. self._summary_file_handler.reset_offset(start_offset)
  85. is_end = True
  86. logger.warning("Check crc failed and ignore this file, file_path=%s, "
  87. "offset=%s.", self._summary_file_handler.file_path, self._summary_file_handler.offset)
  88. return is_clean, is_end, event_data
  89. except (OSError, DecodeError, exceptions.MindInsightException) as ex:
  90. is_end = True
  91. logger.warning("Parse log file fail, and ignore this file, detail: %r,"
  92. "file path: %s.", str(ex), self._summary_file_handler.file_path)
  93. return is_clean, is_end, event_data
  94. except Exception as ex:
  95. logger.exception(ex)
  96. raise UnknownError(str(ex))
  97. def filter_files(self, filenames):
  98. """
  99. Gets a list of summary files.
  100. Args:
  101. filenames (list[str]): File name list, like [filename1, filename2].
  102. Returns:
  103. list[str], filename list.
  104. """
  105. return list(filter(
  106. lambda filename: (re.search(r'summary\.\d+', filename)
  107. and filename.endswith("_explain")), filenames))
  108. @staticmethod
  109. def _event_decode(event_str):
  110. """
  111. Transform `Event` data to tensor_event and update it to EventsData.
  112. Args:
  113. event_str (str): Message event string in summary proto, data read from file handler.
  114. """
  115. logger.debug("Start to parse event string. Event string len: %s.", len(event_str))
  116. event = summary_pb2.Event.FromString(event_str)
  117. logger.debug("Deserialize event string completed.")
  118. fields = {
  119. 'image_id': PluginNameEnum.IMAGE_ID,
  120. 'benchmark': PluginNameEnum.BENCHMARK,
  121. 'metadata': PluginNameEnum.METADATA
  122. }
  123. tensor_event_value = getattr(event, 'explain')
  124. field_list = []
  125. tensor_value_list = []
  126. for field in fields:
  127. if not getattr(tensor_event_value, field):
  128. continue
  129. if PluginNameEnum.METADATA.value == field and not tensor_event_value.metadata.label:
  130. continue
  131. tensor_value = None
  132. if field == PluginNameEnum.IMAGE_ID.value:
  133. tensor_value = _ExplainParser._add_image_data(tensor_event_value)
  134. elif field == PluginNameEnum.BENCHMARK.value:
  135. tensor_value = _ExplainParser._add_benchmark(tensor_event_value)
  136. elif field == PluginNameEnum.METADATA.value:
  137. tensor_value = _ExplainParser._add_metadata(tensor_event_value)
  138. logger.debug("Event generated, label is %s, step is %s.", field, event.step)
  139. field_list.append(field)
  140. tensor_value_list.append(tensor_value)
  141. return field_list, tensor_value_list
  142. @staticmethod
  143. def _add_image_data(tensor_event_value):
  144. """
  145. Parse image data based on image_id in Explain message
  146. Args:
  147. tensor_event_value: the object of Explain message
  148. """
  149. image_data = ImageDataContainer(
  150. image_id=tensor_event_value.image_id,
  151. image_data=tensor_event_value.image_data,
  152. ground_truth_label=tensor_event_value.ground_truth_label,
  153. inference=tensor_event_value.inference,
  154. explanation=tensor_event_value.explanation,
  155. status=tensor_event_value.status
  156. )
  157. return image_data
  158. @staticmethod
  159. def _add_benchmark(tensor_event_value):
  160. """
  161. Parse benchmark data from Explain message.
  162. Args:
  163. tensor_event_value: the object of Explain message
  164. Returns:
  165. benchmark_data: An object containing benchmark.
  166. """
  167. benchmark_data = BenchmarkContainer(
  168. benchmark=tensor_event_value.benchmark,
  169. status=tensor_event_value.status
  170. )
  171. return benchmark_data
  172. @staticmethod
  173. def _add_metadata(tensor_event_value):
  174. """
  175. Parse metadata from Explain message.
  176. Args:
  177. tensor_event_value: the object of Explain message
  178. Returns:
  179. benchmark_data: An object containing metadata.
  180. """
  181. metadata_value = MetadataContainer(
  182. metadata=tensor_event_value.metadata,
  183. status=tensor_event_value.status
  184. )
  185. return metadata_value