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_utils.py 2.1 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 reader."""
  16. import struct
  17. import mindspore.train.summary_pb2 as summary_pb2
  18. _HEADER_SIZE = 8
  19. _HEADER_CRC_SIZE = 4
  20. _DATA_CRC_SIZE = 4
  21. class _EndOfSummaryFileException(Exception):
  22. """Indicates the summary file is exhausted."""
  23. class SummaryReader:
  24. """
  25. Basic summary read function.
  26. Args:
  27. canonical_file_path (str): The canonical summary file path.
  28. ignore_version_event (bool): Whether ignore the version event at the beginning of summary file.
  29. """
  30. def __init__(self, canonical_file_path, ignore_version_event=True):
  31. self._file_path = canonical_file_path
  32. self._ignore_version_event = ignore_version_event
  33. self._file_handler = None
  34. def __enter__(self):
  35. self._file_handler = open(self._file_path, "rb")
  36. if self._ignore_version_event:
  37. self.read_event()
  38. return self
  39. def __exit__(self, *unused_args):
  40. self._file_handler.close()
  41. return False
  42. def read_event(self):
  43. """Read next event."""
  44. file_handler = self._file_handler
  45. header = file_handler.read(_HEADER_SIZE)
  46. data_len = struct.unpack('Q', header)[0]
  47. # Ignore crc check.
  48. file_handler.read(_HEADER_CRC_SIZE)
  49. event_str = file_handler.read(data_len)
  50. # Ignore crc check.
  51. file_handler.read(_DATA_CRC_SIZE)
  52. summary_event = summary_pb2.Event.FromString(event_str)
  53. return summary_event