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.

test_minddata_analyzer.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Copyright 2021 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. Test MindData Profiling Analyzer Support
  17. """
  18. import csv
  19. import json
  20. import os
  21. import numpy as np
  22. import mindspore.common.dtype as mstype
  23. import mindspore.dataset as ds
  24. import mindspore.dataset.transforms.c_transforms as C
  25. from mindspore.profiler.parser.minddata_analyzer import MinddataProfilingAnalyzer
  26. class TestMinddataProfilingAnalyzer():
  27. """
  28. Test the MinddataProfilingAnalyzer class
  29. """
  30. def setup_class(self):
  31. """
  32. Run once for the class
  33. """
  34. # Define filenames and path used for the MinddataProfilingAnalyzer tests. Use device_id=7.
  35. self._PIPELINE_FILE = "./pipeline_profiling_7.json"
  36. self._CPU_UTIL_FILE = "./minddata_cpu_utilization_7.json"
  37. self._DATASET_ITERATOR_FILE = "./dataset_iterator_profiling_7.txt"
  38. self._SUMMARY_JSON_FILE = "./minddata_pipeline_summary_7.json"
  39. self._SUMMARY_CSV_FILE = "./minddata_pipeline_summary_7.csv"
  40. self._ANALYZE_FILE_PATH = "./"
  41. # This is the set of keys for success case
  42. self._EXPECTED_SUMMARY_KEYS_SUCCESS = \
  43. ['avg_cpu_pct', 'avg_cpu_pct_per_worker', 'children_ids', 'num_workers', 'op_ids', 'op_names',
  44. 'parent_id', 'per_batch_time', 'per_pipeline_time', 'per_push_queue_time', 'pipeline_ops',
  45. 'queue_average_size', 'queue_empty_freq_pct', 'queue_utilization_pct']
  46. def setup_method(self):
  47. """
  48. Run before each test function.
  49. """
  50. # Confirm MindData Profiling files do not yet exist
  51. assert os.path.exists(self._PIPELINE_FILE) is False
  52. assert os.path.exists(self._CPU_UTIL_FILE) is False
  53. assert os.path.exists(self._DATASET_ITERATOR_FILE) is False
  54. # Confirm MindData Profiling analyze summary files do not yet exist
  55. assert os.path.exists(self._SUMMARY_JSON_FILE) is False
  56. assert os.path.exists(self._SUMMARY_CSV_FILE) is False
  57. # Set the MindData Profiling environment variables
  58. os.environ['PROFILING_MODE'] = 'true'
  59. os.environ['MINDDATA_PROFILING_DIR'] = '.'
  60. os.environ['RANK_ID'] = '7'
  61. def teardown_method(self):
  62. """
  63. Run after each test function.
  64. """
  65. # Delete MindData profiling files generated from the test.
  66. os.remove(self._PIPELINE_FILE)
  67. os.remove(self._CPU_UTIL_FILE)
  68. os.remove(self._DATASET_ITERATOR_FILE)
  69. # Delete MindData profiling analyze summary files generated from the test.
  70. os.remove(self._SUMMARY_JSON_FILE)
  71. os.remove(self._SUMMARY_CSV_FILE)
  72. # Disable MindData Profiling environment variables
  73. del os.environ['PROFILING_MODE']
  74. del os.environ['MINDDATA_PROFILING_DIR']
  75. del os.environ['RANK_ID']
  76. def get_csv_result(self, file_pathname):
  77. """
  78. Get result from the CSV file.
  79. Args:
  80. file_pathname (str): The CSV file pathname.
  81. Returns:
  82. list[list], the parsed CSV information.
  83. """
  84. result = []
  85. with open(file_pathname, 'r') as csvfile:
  86. csv_reader = csv.reader(csvfile)
  87. for row in csv_reader:
  88. result.append(row)
  89. return result
  90. def verify_md_summary(self, md_summary_dict, EXPECTED_SUMMARY_KEYS):
  91. """
  92. Verify the content of the 3 variations of the MindData Profiling analyze summary output.
  93. """
  94. # Confirm MindData Profiling analyze summary files are created
  95. assert os.path.exists(self._SUMMARY_JSON_FILE) is True
  96. assert os.path.exists(self._SUMMARY_CSV_FILE) is True
  97. # Build a list of the sorted returned keys
  98. summary_returned_keys = list(md_summary_dict.keys())
  99. summary_returned_keys.sort()
  100. # 1. Confirm expected keys are in returned keys
  101. for k in EXPECTED_SUMMARY_KEYS:
  102. assert k in summary_returned_keys
  103. # Read summary JSON file
  104. with open(self._SUMMARY_JSON_FILE) as f:
  105. summary_json_data = json.load(f)
  106. # Build a list of the sorted JSON keys
  107. summary_json_keys = list(summary_json_data.keys())
  108. summary_json_keys.sort()
  109. # 2a. Confirm expected keys are in JSON file keys
  110. for k in EXPECTED_SUMMARY_KEYS:
  111. assert k in summary_json_keys
  112. # 2b. Confirm returned dictionary keys are identical to JSON file keys
  113. np.testing.assert_array_equal(summary_returned_keys, summary_json_keys)
  114. # Read summary CSV file
  115. summary_csv_data = self.get_csv_result(self._SUMMARY_CSV_FILE)
  116. # Build a list of the sorted CSV keys from the first column in the CSV file
  117. summary_csv_keys = []
  118. for x in summary_csv_data:
  119. summary_csv_keys.append(x[0])
  120. summary_csv_keys.sort()
  121. # 3a. Confirm expected keys are in the first column of the CSV file
  122. for k in EXPECTED_SUMMARY_KEYS:
  123. assert k in summary_csv_keys
  124. # 3b. Confirm returned dictionary keys are identical to CSV file first column keys
  125. np.testing.assert_array_equal(summary_returned_keys, summary_csv_keys)
  126. def mysource(self):
  127. """Source for data values"""
  128. for i in range(8000):
  129. yield (np.array([i]),)
  130. def test_analyze_basic(self):
  131. """
  132. Test MindData profiling analyze summary files exist with basic pipeline.
  133. Also test basic content (subset of keys and values) from the returned summary result.
  134. """
  135. # Create this basic and common linear pipeline
  136. # Generator -> Map -> Batch -> Repeat -> EpochCtrl
  137. data1 = ds.GeneratorDataset(self.mysource, ["col1"])
  138. type_cast_op = C.TypeCast(mstype.int32)
  139. data1 = data1.map(operations=type_cast_op, input_columns="col1")
  140. data1 = data1.batch(16)
  141. data1 = data1.repeat(2)
  142. num_iter = 0
  143. # Note: If create_tuple_iterator() is called with num_epochs>1, then EpochCtrlOp is added to the pipeline
  144. for _ in data1.create_dict_iterator(num_epochs=2):
  145. num_iter = num_iter + 1
  146. # Confirm number of rows returned
  147. assert num_iter == 1000
  148. # Confirm MindData Profiling files are created
  149. assert os.path.exists(self._PIPELINE_FILE) is True
  150. assert os.path.exists(self._CPU_UTIL_FILE) is True
  151. assert os.path.exists(self._DATASET_ITERATOR_FILE) is True
  152. # Call MindData Analyzer for generated MindData profiling files to generate MindData pipeline summary result
  153. md_analyzer = MinddataProfilingAnalyzer(self._ANALYZE_FILE_PATH, 7, self._ANALYZE_FILE_PATH)
  154. md_summary_dict = md_analyzer.analyze()
  155. # Verify MindData Profiling Analyze Summary output
  156. # Note: MindData Analyzer returns the result in 3 formats:
  157. # 1. returned dictionary
  158. # 2. JSON file
  159. # 3. CSV file
  160. self.verify_md_summary(md_summary_dict, self._EXPECTED_SUMMARY_KEYS_SUCCESS)
  161. # 4. Verify non-variant values or number of values in the tested pipeline for certain keys
  162. # of the returned dictionary
  163. # Note: Values of num_workers are not tested since default may change in the future
  164. # Note: Values related to queue metrics are not tested since they may vary on different execution environments
  165. assert md_summary_dict["pipeline_ops"] == ["EpochCtrl(id=0)", "Repeat(id=1)", "Batch(id=2)", "Map(id=3)",
  166. "Generator(id=4)"]
  167. assert md_summary_dict["op_names"] == ["EpochCtrl", "Repeat", "Batch", "Map", "Generator"]
  168. assert md_summary_dict["op_ids"] == [0, 1, 2, 3, 4]
  169. assert len(md_summary_dict["num_workers"]) == 5
  170. assert len(md_summary_dict["queue_average_size"]) == 5
  171. assert len(md_summary_dict["queue_utilization_pct"]) == 5
  172. assert len(md_summary_dict["queue_empty_freq_pct"]) == 5
  173. assert md_summary_dict["children_ids"] == [[1], [2], [3], [4], []]
  174. assert md_summary_dict["parent_id"] == [-1, 0, 1, 2, 3]
  175. assert len(md_summary_dict["avg_cpu_pct"]) == 5
  176. def test_analyze_sequential_pipelines_invalid(self):
  177. """
  178. Test invalid scenario in which MinddataProfilingAnalyzer is called for two sequential pipelines.
  179. """
  180. # Create the pipeline
  181. # Generator -> Map -> Batch -> EpochCtrl
  182. data1 = ds.GeneratorDataset(self.mysource, ["col1"])
  183. type_cast_op = C.TypeCast(mstype.int32)
  184. data1 = data1.map(operations=type_cast_op, input_columns="col1")
  185. data1 = data1.batch(64)
  186. # Phase 1 - For the pipeline, call create_tuple_iterator with num_epochs>1
  187. # Note: This pipeline has 4 ops: Generator -> Map -> Batch -> EpochCtrl
  188. num_iter = 0
  189. # Note: If create_tuple_iterator() is called with num_epochs>1, then EpochCtrlOp is added to the pipeline
  190. for _ in data1.create_dict_iterator(num_epochs=2):
  191. num_iter = num_iter + 1
  192. # Confirm number of rows returned
  193. assert num_iter == 125
  194. # Confirm MindData Profiling files are created
  195. assert os.path.exists(self._PIPELINE_FILE) is True
  196. assert os.path.exists(self._CPU_UTIL_FILE) is True
  197. assert os.path.exists(self._DATASET_ITERATOR_FILE) is True
  198. # Phase 2 - For the pipeline, call create_tuple_iterator with num_epochs=1
  199. # Note: This pipeline has 3 ops: Generator -> Map -> Batch
  200. num_iter = 0
  201. # Note: If create_tuple_iterator() is called with num_epochs=1, then EpochCtrlOp is NOT added to the pipeline
  202. for _ in data1.create_dict_iterator(num_epochs=1):
  203. num_iter = num_iter + 1
  204. # Confirm number of rows returned
  205. assert num_iter == 125
  206. # Confirm MindData Profiling files are created
  207. # Note: There is an MD bug in which which the pipeline file is not recreated;
  208. # it still has 4 ops instead of 3 ops
  209. assert os.path.exists(self._PIPELINE_FILE) is True
  210. assert os.path.exists(self._CPU_UTIL_FILE) is True
  211. assert os.path.exists(self._DATASET_ITERATOR_FILE) is True
  212. # Call MindData Analyzer for generated MindData profiling files to generate MindData pipeline summary result
  213. md_analyzer = MinddataProfilingAnalyzer(self._ANALYZE_FILE_PATH, 7, self._ANALYZE_FILE_PATH)
  214. md_summary_dict = md_analyzer.analyze()
  215. # Verify MindData Profiling Analyze Summary output
  216. self.verify_md_summary(md_summary_dict, self._EXPECTED_SUMMARY_KEYS_SUCCESS)
  217. # Confirm pipeline data contains info for 3 ops
  218. assert md_summary_dict["pipeline_ops"] == ["Batch(id=0)", "Map(id=1)", "Generator(id=2)"]
  219. # Verify CPU util data contains info for 3 ops
  220. assert len(md_summary_dict["avg_cpu_pct"]) == 3