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 13 kB

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