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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 marshmallow import ValidationError
  19. from tabulate import tabulate
  20. from mindinsight.profiler.analyser.analyser_factory import AnalyserFactory
  21. from mindinsight.profiler.analyser.integrator import Integrator
  22. from mindinsight.profiler.common._utils import get_file_names, fwrite_format
  23. from mindinsight.profiler.common.exceptions.exceptions import ProfilerFileNotFoundException, \
  24. ProfilerIOException
  25. from mindinsight.profiler.common.log import logger
  26. from mindinsight.profiler.common.validator.checkparam import \
  27. check_bool, check_subgraph
  28. from mindinsight.profiler.common.validator.validate_path import \
  29. validate_and_normalize_path
  30. from mindinsight.profiler.parser.aicpu_data_parser import DataPreProcessParser
  31. from mindinsight.profiler.parser.framework_parser import FrameworkParser
  32. from mindinsight.profiler.parser.hwts_log_parser import HWTSLogParser
  33. from mindinsight.profiler.parser.minddata_parser import MinddataParser
  34. from mindinsight.profiler.parser.minddata_pipeline_parser import \
  35. MinddataPipelineParser
  36. from mindinsight.profiler.parser.optime_parser import OPComputeTimeParser
  37. from mindinsight.profiler.parser.step_trace_parser import StepTraceParser
  38. from mindinsight.utils.exceptions import MindInsightException
  39. PROFILING_LOG_BASE_PATH = "/var/log/npu/profiling"
  40. INIT_OP_NAME = 'Default/InitDataSetQueue'
  41. class Profiler:
  42. """
  43. Performance profiling API.
  44. Enable MindSpore users to profile the performance of neural network.
  45. Args:
  46. subgraph (str): Define which subgraph to monitor and analyse, can be 'all', 'Default', 'Gradients'.
  47. is_detail (bool): Whether to show profiling data for op_instance level, only show optype level if False.
  48. is_show_op_path (bool): Whether to save the full path for each op instance.
  49. output_path (str): Output data path.
  50. optypes_to_deal (str): Op type names, the data of which optype should be collected and analysed,
  51. will deal with all op if null; Different op types should be seperated by comma.
  52. optypes_not_deal (str): Op type names, the data of which optype will not be collected and analysed;
  53. Different op types should be seperated by comma.
  54. Examples:
  55. >>> from mindinsight.profiler import Profiler
  56. >>> context.set_context(mode=context.GRAPH_MODE, device_target="Ascend",
  57. >>> device_id=int(os.environ["DEVICE_ID"]))
  58. >>> profiler = Profiler(subgraph='all', is_detail=True, is_show_op_path=False, output_path='./data')
  59. >>> model = Model(train_network)
  60. >>> dataset = get_dataset()
  61. >>> model.train(2, dataset)
  62. >>> profiler.analyse()
  63. """
  64. _base_profiling_container_path = "/var/log/npu/profiling/container"
  65. _hwts_output_filename_target = "output_format_data_hwts_"
  66. _opcompute_output_filename_target = "output_op_compute_time_"
  67. _aicpu_op_output_filename_target = "output_data_preprocess_aicpu_"
  68. def __init__(self, subgraph='all', is_detail=True, is_show_op_path=False, output_path='./data',
  69. optypes_to_deal='', optypes_not_deal='Variable', job_id=""):
  70. # get device_id and device_target
  71. device_target = ""
  72. dev_id = ""
  73. try:
  74. import mindspore.context as context
  75. dev_id = str(context.get_context("device_id"))
  76. device_target = context.get_context("device_target")
  77. except ImportError:
  78. logger.error("Profiling: fail to import context from mindspore.")
  79. except ValueError as err:
  80. logger.error("Profiling: fail to get context, %s", err)
  81. if not dev_id:
  82. dev_id = os.getenv('DEVICE_ID')
  83. if not dev_id:
  84. dev_id = "0"
  85. logger.error("Fail to get DEVICE_ID, use 0 instead.")
  86. if device_target and device_target != "Davinci" \
  87. and device_target != "Ascend":
  88. msg = ("Profiling: unsupport backend: %s" \
  89. % device_target)
  90. raise RuntimeError(msg)
  91. self._dev_id = dev_id
  92. self._container_path = os.path.join(self._base_profiling_container_path, dev_id)
  93. data_path = os.path.join(self._container_path, "data")
  94. if not os.path.exists(data_path):
  95. os.makedirs(data_path)
  96. self._output_path = validate_and_normalize_path(output_path,
  97. 'Profiler output path (' + output_path + ')')
  98. self._output_path = os.path.join(self._output_path, "profiler")
  99. if not os.path.exists(self._output_path):
  100. os.makedirs(self._output_path)
  101. os.environ['PROFILING_MODE'] = 'true'
  102. os.environ['PROFILING_OPTIONS'] = 'training_trace:task_trace'
  103. os.environ['MINDDATA_PROFILING_DIR'] = self._output_path
  104. # use context interface to open profiling, for the new mindspore version(after 2020.5.21)
  105. try:
  106. import mindspore.context as context
  107. context.set_context(enable_profiling=True, profiling_options="training_trace:task_trace")
  108. except ImportError:
  109. logger.error("Profiling: fail to import context from mindspore.")
  110. except ValueError as err:
  111. logger.error("Profiling: fail to set context, %s", err.message)
  112. os.environ['AICPU_PROFILING_MODE'] = 'true'
  113. os.environ['PROFILING_DIR'] = str(self._container_path)
  114. self._subgraph = check_subgraph(subgraph)
  115. self._valid_optype_name = optypes_to_deal.split(",") if optypes_to_deal else []
  116. self._filt_optype_names = optypes_not_deal.split(",") if optypes_not_deal else []
  117. self._detail = check_bool(is_detail, 'is_detail')
  118. self._withfullpath = check_bool(is_show_op_path, 'is_show_op_path')
  119. self._profiling_job_id = job_id
  120. # add job id env through user input later
  121. self._job_id_env = 0
  122. self._start_time = int(time.time() * 10000000)
  123. logger.info("Profiling: profiling start time: %d", self._start_time)
  124. def analyse(self):
  125. """
  126. Collect and analyse performance data, called after training or during training.
  127. Examples:
  128. >>> from mindinsight.profiler import Profiler
  129. >>> context.set_context(mode=context.GRAPH_MODE, device_target="Ascend",
  130. >>> device_id=int(os.environ["DEVICE_ID"]))
  131. >>> profiler = Profiler(subgraph='all', is_detail=True, is_show_op_path=False, output_path='./data')
  132. >>> model = Model(train_network)
  133. >>> dataset = get_dataset()
  134. >>> model.train(2, dataset)
  135. >>> profiler.analyse()
  136. """
  137. try:
  138. from mindspore.communication.management import release
  139. release()
  140. except ImportError:
  141. logger.error("Profiling: fail to import release from mindspore.")
  142. logger.info("begin profiler analyse")
  143. job_id = self._get_profiling_job_id()
  144. if not job_id:
  145. msg = ("Fail to get profiling job, please check whether job dir was generated under path %s" \
  146. % PROFILING_LOG_BASE_PATH)
  147. raise RuntimeError(msg)
  148. logger.info("Profiling: job id is %s ", job_id)
  149. source_path = os.path.join(PROFILING_LOG_BASE_PATH, job_id)
  150. # parse hwts.log.data.45.dev file, and get task profiling data
  151. hwts_output_filename = self._hwts_output_filename_target + self._dev_id + ".txt"
  152. hwts_output_filename = os.path.join(self._output_path, hwts_output_filename)
  153. hwtslog_parser = HWTSLogParser(source_path, hwts_output_filename)
  154. result = hwtslog_parser.execute()
  155. if not result:
  156. logger.error("Profiling: fail to parse hwts log file.")
  157. return
  158. # parse Framework file, and get the relation of op and tasks
  159. framework_parser = FrameworkParser(job_id, self._dev_id, self._output_path)
  160. framework_parser.parse()
  161. op_task_dict = framework_parser.to_task_id_full_op_name_dict()
  162. if not op_task_dict:
  163. logger.error("Profiling: fail to parse framework files.")
  164. return
  165. # get op compute time from hwts data and framework data, write output_op_compute_time.txt
  166. opcompute_output_filename = self._opcompute_output_filename_target + self._dev_id + ".txt"
  167. opcompute_output_filename = os.path.join(self._output_path, opcompute_output_filename)
  168. optime_parser = OPComputeTimeParser(
  169. hwts_output_filename, opcompute_output_filename,
  170. op_task_dict, self._output_path, self._dev_id
  171. )
  172. optime_parser.execute()
  173. # parse DATA_PREPROCESS.dev.AICPU file, write output_data_preprocess_aicpu_x.txt
  174. output_data_preprocess_aicpu = self._aicpu_op_output_filename_target + self._dev_id + ".txt"
  175. output_data_preprocess_aicpu = os.path.join(self._output_path, output_data_preprocess_aicpu)
  176. try:
  177. aicpu_data_parser = DataPreProcessParser(source_path, output_data_preprocess_aicpu)
  178. aicpu_data_parser.execute()
  179. except FileNotFoundError as err:
  180. logger.exception(err)
  181. # Parsing minddata AICPU profiling
  182. MinddataParser.execute(source_path, self._output_path, self._dev_id)
  183. # parse minddata pipeline operator and queue
  184. try:
  185. pipeline_parser = MinddataPipelineParser(job_id, self._dev_id)
  186. pipeline_parser.parse()
  187. except MindInsightException as err:
  188. logger.warning(err.message)
  189. # analyse op compute time info
  190. try:
  191. self._analyser_op_info()
  192. except MindInsightException as err:
  193. logger.warning(err.message)
  194. # analyse step trace info
  195. self._analyse_step_trace(source_path, framework_parser)
  196. # analyse timeline info
  197. self._analyse_timeline()
  198. def _analyse_step_trace(self, source_path, framework_parser):
  199. """
  200. Analyse step trace data and save the result.
  201. Args:
  202. source_path (str): The directory that contains the step trace original data.
  203. framework_parser (FrameworkParser): The framework parse instance.
  204. """
  205. logger.info("Begin to parse step trace.")
  206. # construct output path
  207. step_trace_intermediate_file_path = os.path.join(
  208. self._output_path,
  209. f'step_trace_raw_{self._dev_id}_detail_time.csv'
  210. )
  211. # whether keep the first step
  212. skip_first_step_flag = framework_parser.check_op_name(INIT_OP_NAME)
  213. # parser the step trace files and save the result to disk
  214. parser = StepTraceParser(input_dir=source_path,
  215. output_file_path=step_trace_intermediate_file_path,
  216. job_id=self._job_id_env,
  217. skip_first_step=skip_first_step_flag)
  218. parser.parse_and_save()
  219. # print parser result
  220. parser.show()
  221. def _analyse_timeline(self):
  222. """
  223. Analyse and parse timeline info.
  224. """
  225. # Get framework info
  226. aicoredetail_analyser = AnalyserFactory.instance().get_analyser(
  227. 'aicore_detail', self._output_path, self._dev_id
  228. )
  229. framework_info = aicoredetail_analyser.query()
  230. # Get all reduce info
  231. step_trace_analyser = AnalyserFactory.instance().get_analyser(
  232. 'step_trace', self._output_path, self._dev_id
  233. )
  234. all_reduce_info = step_trace_analyser.query_for_all_reduce()
  235. # Get timeline info
  236. timeline_analyser = AnalyserFactory.instance().get_analyser(
  237. 'timeline', self._output_path, self._dev_id
  238. )
  239. timeline_analyser.add_framework_info(framework_info)
  240. timeline_analyser.add_all_reduce_info(all_reduce_info)
  241. try:
  242. timeline_analyser.write_timeline()
  243. timeline_analyser.write_timeline_summary()
  244. except (ProfilerIOException, ProfilerFileNotFoundException, ValidationError) as err:
  245. logger.warning('Fail to write timeline data: %s', err)
  246. def __del__(self):
  247. """Disable the profiling collection service, called after training."""
  248. os.environ['PROFILING_MODE'] = str("false")
  249. def _get_profiling_job_id(self):
  250. """Get profiling job id, which was generated by ada service.
  251. Returns:
  252. str: profiling jon id.
  253. """
  254. if self._profiling_job_id:
  255. return self._profiling_job_id
  256. job_id = ""
  257. cmd = "ls -t " + PROFILING_LOG_BASE_PATH + "|grep JOB|awk '{print $1}'"
  258. r = os.popen(cmd)
  259. profiling_job_dirs = r.readlines()
  260. r.close()
  261. for item in profiling_job_dirs:
  262. path = os.path.join(PROFILING_LOG_BASE_PATH, item.strip())
  263. log_file = get_file_names(path, "host_start.log")
  264. if not log_file:
  265. logger.error("Profiling: job path %s, host_start.log not exist.", path)
  266. continue
  267. log_file = os.path.join(path, log_file[0])
  268. item_dict = self._parse_host_start_log(log_file)
  269. if not item_dict:
  270. logger.error("Profiling: job path %s, fail to get job start info.", path)
  271. continue
  272. if self._start_time > int(item_dict["start_time"]):
  273. logger.info("Profiling: job path %s, start_time %s, training start_time %d.",
  274. path, item_dict["start_time"], self._start_time)
  275. break
  276. if self._dev_id != item_dict["device_id"]:
  277. logger.info("Profiling: job path %s, dev id %s, training device id %s.",
  278. path, item_dict["device_id"], self._dev_id)
  279. continue
  280. job_id = item.strip()
  281. break
  282. return job_id
  283. def _parse_host_start_log(self, input_file):
  284. """
  285. Parse host start log file, get the device id and start time of the job.
  286. Args:
  287. input_file (str): The file path of the host start log file.
  288. Returns:
  289. dict, job start time and device id.
  290. """
  291. item_dict = {}
  292. for line in open(input_file):
  293. if "Device" in line:
  294. item_dict["device_id"] = line[7:len(line)-2]
  295. elif "clock_realtime" in line:
  296. item_dict["start_time"] = line[16:len(line)-3]
  297. return item_dict
  298. def _analyser_op_info(self):
  299. """Analyse the operator information."""
  300. integrator = Integrator(self._output_path, self._dev_id)
  301. integrator.integrate()
  302. aicore_type_result = self._query_op_type_info()
  303. detail_file_path = os.path.join(
  304. self._output_path,
  305. 'output_op_compute_time_detail_{}.txt'.format(self._dev_id)
  306. )
  307. fwrite_format(detail_file_path, data_source='title:op compute time')
  308. display_names = [
  309. 'optype_name', 'compute_time(ms, per-step)',
  310. 'called_times(per-step)', 'percent'
  311. ]
  312. data_source = tabulate(aicore_type_result, display_names)
  313. fwrite_format(detail_file_path, data_source=data_source, is_print=True)
  314. if self._detail:
  315. op_type_order = [item[0] for item in aicore_type_result]
  316. aicore_detail_result = self._query_op_detail_info(op_type_order)
  317. fwrite_format(detail_file_path, data_source='', is_print=True)
  318. fwrite_format(detail_file_path, data_source='Detail:', is_print=True)
  319. data_source = tabulate(
  320. aicore_detail_result.get('object'),
  321. aicore_detail_result.get('col_name')
  322. )
  323. fwrite_format(detail_file_path, data_source=data_source, is_print=True)
  324. def _query_op_type_info(self):
  325. """
  326. Query AICORE operator type information.
  327. Returns:
  328. list[list], the AICORE operator type and execution time information.
  329. """
  330. condition = {
  331. 'sort_condition': {
  332. 'name': 'execution_time',
  333. 'type': 'descending'
  334. }
  335. }
  336. analyser = AnalyserFactory.instance().get_analyser(
  337. 'aicore_type', self._output_path, self._dev_id
  338. )
  339. result = analyser.query(condition)
  340. return result.get('object')
  341. def _query_op_detail_info(self, op_type_order):
  342. """
  343. Query AICORE operator detail information.
  344. Args:
  345. op_type_order(list): The name of the op type in order.
  346. Returns:
  347. dict, the AICORE operator detail information.
  348. """
  349. op_type_condition = {}
  350. if self._valid_optype_name:
  351. op_type_condition['in'] = self._valid_optype_name
  352. if self._filt_optype_names:
  353. op_type_condition['not_in'] = self._filt_optype_names
  354. subgraph_condition = {}
  355. if self._subgraph != 'all':
  356. subgraph_condition['in'] = [self._subgraph]
  357. filter_condition = {
  358. 'op_type': op_type_condition,
  359. 'subgraph': subgraph_condition,
  360. 'is_display_detail': False,
  361. 'is_display_full_op_name': self._withfullpath
  362. }
  363. analyser = AnalyserFactory.instance().get_analyser(
  364. 'aicore_detail', self._output_path, self._dev_id
  365. )
  366. result = analyser.query_and_sort_by_op_type(
  367. filter_condition, op_type_order
  368. )
  369. return result