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

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