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.

profiling.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. """Profiling api file."""
  16. import os
  17. import time
  18. from tabulate import tabulate
  19. from mindinsight.profiler.parser.hwts_log_parser import HWTSLogParser
  20. from mindinsight.profiler.parser.framework_parser import FrameworkParser
  21. from mindinsight.profiler.parser.optime_parser import OPComputeTimeParser
  22. from mindinsight.profiler.parser.aicpu_data_parser import DataPreProcessParser
  23. from mindinsight.profiler.analyser.analyser_factory import AnalyserFactory
  24. from mindinsight.profiler.analyser.integrator import Integrator
  25. from mindinsight.profiler.common._utils import get_file_names, fwrite_format
  26. from mindinsight.profiler.common.validator.validate_path import \
  27. validate_and_normalize_path
  28. from mindinsight.profiler.common.validator.checkparam import \
  29. check_bool, check_subgraph
  30. from mindinsight.profiler.common.log import logger
  31. from mindinsight.utils.exceptions import MindInsightException
  32. PROFILING_LOG_BASE_PATH = "/var/log/npu/profiling"
  33. class Profiler:
  34. """
  35. Performance profiling API.
  36. Enable MindSpore users to profile the neural network.
  37. Args:
  38. subgraph (str): Defines which subgraph to monitor and analyse, can be 'all', 'Default', 'Gradients'.
  39. is_detail (bool): Whether to show profiling data for op_instance level, only show optype level if False.
  40. is_show_op_path (bool): Whether to save the full path for each op instance.
  41. output_path (str): Output data path.
  42. optypes_to_deal (list): Op type names, the data of which optype should be collected and analysed,
  43. will deal with all op if null.
  44. optypes_not_deal (list): Op type names, the data of which optype will not be collected and analysed.
  45. Examples:
  46. >>> from mindinsight.profiler import Profiler
  47. >>> profiler = Profiler(subgraph='all', is_detail=True, is_show_op_path=False, output_path='./data')
  48. >>> model = Model(train_network)
  49. >>> dataset = get_dataset()
  50. >>> model.train(2, dataset)
  51. >>> profiler.analyse()
  52. """
  53. _base_profiling_container_path = "/var/log/npu/profiling/container"
  54. _hwts_output_filename_target = "output_format_data_hwts_"
  55. _opcompute_output_filename_target = "output_op_compute_time_"
  56. _aicpu_op_output_filename_target = "output_data_preprocess_aicpu_"
  57. def __init__(self, subgraph='all', is_detail=True, is_show_op_path=False, output_path='./data',
  58. optypes_to_deal='', optypes_not_deal='Variable', job_id=""):
  59. dev_id = os.getenv('DEVICE_ID')
  60. if not dev_id:
  61. dev_id = "0"
  62. logger.error("Fail to get DEVICE_ID, use 0 instead.")
  63. self._dev_id = dev_id
  64. self._container_path = os.path.join(self._base_profiling_container_path, dev_id)
  65. data_path = os.path.join(self._container_path, "data")
  66. if not os.path.exists(data_path):
  67. os.makedirs(data_path)
  68. self._output_path = validate_and_normalize_path(output_path,
  69. 'Profiler output path (' + output_path + ')')
  70. self._output_path = os.path.join(self._output_path, "profiler")
  71. if not os.path.exists(self._output_path):
  72. os.makedirs(self._output_path)
  73. os.environ['PROFILING_MODE'] = 'true'
  74. os.environ['PROFILING_OPTIONS'] = 'training_trace:task_trace'
  75. os.environ['AICPU_PROFILING_MODE'] = 'true'
  76. os.environ['PROFILING_DIR'] = str(self._container_path)
  77. self._subgraph = check_subgraph(subgraph)
  78. self._valid_optype_name = optypes_to_deal.split(",") if optypes_to_deal else []
  79. self._filt_optype_names = optypes_not_deal.split(",") if optypes_not_deal else []
  80. self._detail = check_bool(is_detail, 'is_detail')
  81. self._withfullpath = check_bool(is_show_op_path, 'is_show_op_path')
  82. self._profiling_job_id = job_id
  83. self._start_time = int(time.time() * 10000000)
  84. logger.info("Profiling: profiling start time: %d", self._start_time)
  85. def analyse(self):
  86. """
  87. Collect and analyse performance data, called after training or during training.
  88. Examples:
  89. >>> from mindinsight.profiler import Profiler
  90. >>> profiler = Profiler(subgraph='all', is_detail=True, is_show_op_path=False, output_path='./data')
  91. >>> model = Model(train_network)
  92. >>> dataset = get_dataset()
  93. >>> model.train(2, dataset)
  94. >>> profiler.analyse()
  95. """
  96. try:
  97. from mindspore.communication.management import release
  98. release()
  99. except ImportError:
  100. logger.error("Profiling: fail to import release from mindspore.")
  101. logger.info("begin profiler analyse")
  102. job_id = self._get_profiling_job_id()
  103. if not job_id:
  104. msg = ("Fail to get profiling job, please check whether job dir was generated under path %s" \
  105. % PROFILING_LOG_BASE_PATH)
  106. raise RuntimeError(msg)
  107. logger.info("Profiling: job id is %s ", job_id)
  108. source_path = os.path.join(PROFILING_LOG_BASE_PATH, job_id)
  109. # parse hwts.log.data.45.dev file, and get task profiling data
  110. hwts_output_filename = self._hwts_output_filename_target + self._dev_id + ".txt"
  111. hwts_output_filename = os.path.join(self._output_path, hwts_output_filename)
  112. hwtslog_parser = HWTSLogParser(source_path, hwts_output_filename)
  113. result = hwtslog_parser.execute()
  114. if not result:
  115. logger.error("Profiling: fail to parse hwts log file.")
  116. return
  117. # parse Framework file, and get the relation of op and tasks
  118. framework_parser = FrameworkParser(job_id, self._dev_id, self._output_path)
  119. framework_parser.parse()
  120. op_task_dict = framework_parser.to_task_id_full_op_name_dict()
  121. if not op_task_dict:
  122. logger.error("Profiling: fail to parse framework files.")
  123. return
  124. # get op compute time from hwts data and framework data, write output_op_compute_time.txt
  125. opcompute_output_filename = self._opcompute_output_filename_target + self._dev_id + ".txt"
  126. opcompute_output_filename = os.path.join(self._output_path, opcompute_output_filename)
  127. optime_parser = OPComputeTimeParser(hwts_output_filename, opcompute_output_filename, op_task_dict)
  128. optime_parser.execute()
  129. # parse DATA_PREPROCESS.dev.AICPU file, write output_data_preprocess_aicpu_x.txt
  130. output_data_preprocess_aicpu = self._aicpu_op_output_filename_target + self._dev_id + ".txt"
  131. output_data_preprocess_aicpu = os.path.join(self._output_path, output_data_preprocess_aicpu)
  132. aicpu_data_parser = DataPreProcessParser(source_path, output_data_preprocess_aicpu)
  133. aicpu_data_parser.execute()
  134. # analyse op compute time info
  135. try:
  136. self._analyser_op_info()
  137. except MindInsightException as err:
  138. logger.error(err.message)
  139. def __del__(self):
  140. """Disable the profiling collection service, called after training."""
  141. os.environ['PROFILING_MODE'] = str("false")
  142. def _get_profiling_job_id(self):
  143. """Get profiling job id, which was generated by ada service.
  144. Returns:
  145. str: profiling jon id.
  146. """
  147. if self._profiling_job_id:
  148. return self._profiling_job_id
  149. job_id = ""
  150. cmd = "ls -t " + PROFILING_LOG_BASE_PATH + "|grep JOB|awk '{print $1}'"
  151. r = os.popen(cmd)
  152. profiling_job_dirs = r.readlines()
  153. r.close()
  154. for item in profiling_job_dirs:
  155. path = os.path.join(PROFILING_LOG_BASE_PATH, item.strip())
  156. log_file = get_file_names(path, "host_start.log")
  157. if not log_file:
  158. logger.error("Profiling: job path %s, host_start.log not exist.", path)
  159. continue
  160. log_file = os.path.join(path, log_file[0])
  161. item_dict = self._parse_host_start_log(log_file)
  162. if not item_dict:
  163. logger.error("Profiling: job path %s, fail to get job start info.", path)
  164. continue
  165. if self._start_time > int(item_dict["start_time"]):
  166. logger.info("Profiling: job path %s, start_time %s, training start_time %d.",
  167. path, item_dict["start_time"], self._start_time)
  168. break
  169. if self._dev_id != item_dict["device_id"]:
  170. logger.info("Profiling: job path %s, dev id %s, training device id %s.",
  171. path, item_dict["device_id"], self._dev_id)
  172. continue
  173. job_id = item.strip()
  174. break
  175. return job_id
  176. def _parse_host_start_log(self, input_file):
  177. """
  178. Parse host start log file, get the device id and start time of the job.
  179. Args:
  180. input_file (str): The file path of the host start log file.
  181. Returns:
  182. dict, job start time and device id.
  183. """
  184. item_dict = {}
  185. for line in open(input_file):
  186. if "Device" in line:
  187. item_dict["device_id"] = line[7:len(line)-2]
  188. elif "clock_realtime" in line:
  189. item_dict["start_time"] = line[16:len(line)-3]
  190. return item_dict
  191. def _analyser_op_info(self):
  192. """Analyse the operator information."""
  193. integrator = Integrator(self._output_path, self._dev_id)
  194. integrator.integrate()
  195. aicore_type_result = self._query_op_type_info()
  196. detail_file_path = os.path.join(
  197. self._output_path,
  198. 'output_op_compute_time_detail_{}.txt'.format(self._dev_id)
  199. )
  200. fwrite_format(detail_file_path, data_source='title:op compute time')
  201. display_names = [
  202. 'optype_name', 'compute_time(ms, per-step)',
  203. 'called_times(per-step)', 'percent'
  204. ]
  205. data_source = tabulate(aicore_type_result, display_names)
  206. fwrite_format(detail_file_path, data_source=data_source, is_print=True)
  207. if self._detail:
  208. op_type_order = [item[0] for item in aicore_type_result]
  209. aicore_detail_result = self._query_op_detail_info(op_type_order)
  210. fwrite_format(detail_file_path, data_source='', is_print=True)
  211. fwrite_format(detail_file_path, data_source='Detail:', is_print=True)
  212. data_source = tabulate(
  213. aicore_detail_result.get('object'),
  214. aicore_detail_result.get('col_name')
  215. )
  216. fwrite_format(detail_file_path, data_source=data_source, is_print=True)
  217. def _query_op_type_info(self):
  218. """
  219. Query AICORE operator type information.
  220. Returns:
  221. list[list], the AICORE operator type and execution time information.
  222. """
  223. condition = {
  224. 'sort_condition': {
  225. 'name': 'execution_time',
  226. 'type': 'descending'
  227. }
  228. }
  229. analyser = AnalyserFactory.instance().get_analyser(
  230. 'aicore_type', self._output_path, self._dev_id
  231. )
  232. result = analyser.query(condition)
  233. return result.get('object')
  234. def _query_op_detail_info(self, op_type_order):
  235. """
  236. Query AICORE operator detail information.
  237. Args:
  238. op_type_order(list): The name of the op type in order.
  239. Returns:
  240. dict, the AICORE operator detail information.
  241. """
  242. op_type_condition = {}
  243. if self._valid_optype_name:
  244. op_type_condition['in'] = self._valid_optype_name
  245. if self._filt_optype_names:
  246. op_type_condition['not_in'] = self._filt_optype_names
  247. subgraph_condition = {}
  248. if self._subgraph != 'all':
  249. subgraph_condition['in'] = [self._subgraph]
  250. filter_condition = {
  251. 'op_type': op_type_condition,
  252. 'subgraph': subgraph_condition,
  253. 'is_display_detail': False,
  254. 'is_display_full_op_name': self._withfullpath
  255. }
  256. analyser = AnalyserFactory.instance().get_analyser(
  257. 'aicore_detail', self._output_path, self._dev_id
  258. )
  259. result = analyser.query_and_sort_by_op_type(
  260. filter_condition, op_type_order
  261. )
  262. return result