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

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