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.

integrator.py 29 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. """The integrator for integrating parsed profiling files."""
  16. import csv
  17. import json
  18. import os
  19. from decimal import Decimal
  20. from mindspore import log as logger
  21. from mindspore.profiler.common.exceptions.exceptions import ProfilerIOException, \
  22. ProfilerFileNotFoundException, ProfilerRawFileException
  23. from mindspore.profiler.common.util import query_latest_trace_time_file, to_int, to_millisecond
  24. from mindspore.profiler.common.validator.validate_path import validate_and_normalize_path
  25. from mindspore.profiler.parser.container import TimelineContainer
  26. SIZE_LIMIT = 20 * 1024 * 1024 # 20MB
  27. class Integrator:
  28. """
  29. The integrator for integrating parsed profiling files.
  30. Args:
  31. profiling_dir (str): The directory where the parsed profiling files are
  32. located.
  33. device_id (str): The device ID.
  34. """
  35. _file_name_aicore_detail_time = 'output_op_compute_time_{}.txt'
  36. _file_name_aicpu_time = 'output_data_preprocess_aicpu_{}.txt'
  37. _file_name_framework = 'framework_raw_{}.csv'
  38. _header_aicore_type = ['op_type', 'execution_time', 'execution_frequency',
  39. 'percent']
  40. _header_aicore_detail = ['full_op_name', 'execution_time']
  41. _header_aicpu = ['serial_number', 'op_type', 'total_time', 'dispatch_time',
  42. 'run_start', 'run_end']
  43. _file_name_aicore_type_time = 'aicore_intermediate_{}_type.csv'
  44. _file_name_aicore_detail_info = 'aicore_intermediate_{}_detail.csv'
  45. _col_names_detail = ['op_name', 'op_type', 'avg_execution_time', 'subgraph', 'full_op_name', 'op_info']
  46. _none_filter_condition_key = ['is_display_detail', 'is_display_full_op_name']
  47. _none_sort_col_names = ['op_info']
  48. _aicore_data = []
  49. _aicore_detail_data = []
  50. _aicore_trace_data = []
  51. def __init__(self, profiling_dir, device_id):
  52. self._profiling_dir = profiling_dir
  53. self._device_id = device_id
  54. self._op_time_cache = {}
  55. self._total_time = Decimal('0.0')
  56. def integrate(self):
  57. """Integrate the parsed profiling files."""
  58. self._parse_aicore_detail_time()
  59. self._parse_aicore_type_time()
  60. self._parse_aicpu_time()
  61. def get_aicore_data(self):
  62. self._aicore_data_load()
  63. return self._aicore_data
  64. def get_aicore_detail_data(self):
  65. self._aicore_detail_data_load()
  66. return self._aicore_detail_data
  67. def get_aicore_trace_data(self):
  68. self._aicore_trace_data_load()
  69. return self._aicore_trace_data
  70. def query_for_all_reduce(self):
  71. return self._query_for_all_reduce()
  72. def query_and_sort_by_op_type(self, filter_condition, op_type_order):
  73. return self._query_and_sort_by_op_type(filter_condition, op_type_order)
  74. def _parse_aicore_type_time(self):
  75. """Parse the parsed AICORE operator type file."""
  76. framework_file = os.path.join(
  77. self._profiling_dir,
  78. self._file_name_framework.format(self._device_id)
  79. )
  80. if not os.path.isfile(framework_file):
  81. return
  82. op_name_type_cache = {}
  83. with open(framework_file, 'r') as src_file:
  84. csv_reader = csv.reader(src_file)
  85. _ = next(csv_reader)
  86. for row in csv_reader:
  87. op_name_type_cache[row[3]] = row[5]
  88. op_type_time_cache = {}
  89. for full_op_name, op_time in self._op_time_cache.items():
  90. op_type = op_name_type_cache.get(full_op_name)
  91. if op_type_time_cache.get(op_type) is None:
  92. op_type_time_cache[op_type] = [op_time, 1]
  93. else:
  94. op_type_time_cache[op_type][0] += op_time
  95. op_type_time_cache[op_type][1] += 1
  96. op_type_file_name = 'aicore_intermediate_' + self._device_id + '_type.csv'
  97. op_type_file_path = os.path.join(self._profiling_dir, op_type_file_name)
  98. with open(op_type_file_path, 'w') as type_file:
  99. csv_writer = csv.writer(type_file)
  100. csv_writer.writerow(self._header_aicore_type)
  101. for op_type, op_type_time_info in op_type_time_cache.items():
  102. type_info = [
  103. op_type, op_type_time_info[0], op_type_time_info[1],
  104. round((op_type_time_info[0] / self._total_time) * 100, 2)
  105. ]
  106. csv_writer.writerow(type_info)
  107. def _parse_aicore_detail_time(self):
  108. """Parse the parsed AICORE operator time file."""
  109. aicore_detail_file = os.path.join(
  110. self._profiling_dir,
  111. self._file_name_aicore_detail_time.format(self._device_id)
  112. )
  113. if not os.path.isfile(aicore_detail_file):
  114. return
  115. op_detail_file_name = 'aicore_intermediate_' + self._device_id + '_detail.csv'
  116. op_detail_file_path = os.path.join(
  117. self._profiling_dir, op_detail_file_name
  118. )
  119. with open(aicore_detail_file, 'r') as src_file:
  120. row = src_file.readline()
  121. if row.startswith('op_name'):
  122. _ = src_file.readline()
  123. elif row.startswith('====='):
  124. _ = src_file.readline()
  125. _ = src_file.readline()
  126. else:
  127. return
  128. with open(op_detail_file_path, 'w') as detail_file:
  129. csv_writer = csv.writer(detail_file)
  130. csv_writer.writerow(self._header_aicore_detail)
  131. while True:
  132. row = src_file.readline()
  133. if not row:
  134. break
  135. op_infos = row.split()
  136. if op_infos[0] == 'total':
  137. self._total_time = Decimal(op_infos[2])
  138. continue
  139. self._op_time_cache[op_infos[0]] = Decimal(op_infos[1])
  140. csv_writer.writerow([op_infos[0], op_infos[1]])
  141. def _parse_aicpu_time(self):
  142. """Parse the parsed AICPU operator time file."""
  143. aicpu_file = os.path.join(
  144. self._profiling_dir,
  145. self._file_name_aicpu_time.format(self._device_id)
  146. )
  147. if not os.path.isfile(aicpu_file):
  148. return
  149. save_file_name = 'aicpu_intermediate_' + self._device_id + '.csv'
  150. save_file_path = os.path.join(self._profiling_dir, save_file_name)
  151. with open(aicpu_file, 'r') as src_file:
  152. row = src_file.readline()
  153. if not row.startswith('serial_number'):
  154. return
  155. with open(save_file_path, 'w') as save_file:
  156. csv_writer = csv.writer(save_file)
  157. csv_writer.writerow(self._header_aicpu)
  158. while True:
  159. row = src_file.readline()
  160. if not row:
  161. break
  162. infos = row.split()
  163. if infos[0] == 'AI':
  164. continue
  165. csv_writer.writerow(infos)
  166. def _aicore_data_load(self):
  167. """Load data according to the parsed AICORE operator types file."""
  168. op_type_file_path = os.path.join(
  169. self._profiling_dir,
  170. self._file_name_aicore_type_time.format(self._device_id)
  171. )
  172. if not os.path.isfile(op_type_file_path):
  173. logger.warning('The file <%s> does not exist.', op_type_file_path)
  174. return
  175. with open(op_type_file_path, 'r') as file:
  176. csv_reader = csv.reader(file)
  177. _ = next(csv_reader)
  178. for info in csv_reader:
  179. self._aicore_data.append([info[0], float(info[1]), int(info[2]), float(info[3])])
  180. def _aicore_detail_data_load(self):
  181. """Load data according to the parsed AICORE operator file."""
  182. op_detail_file_path = os.path.join(
  183. self._profiling_dir,
  184. self._file_name_aicore_detail_info.format(self._device_id)
  185. )
  186. framework_file_path = os.path.join(
  187. self._profiling_dir,
  188. self._file_name_framework.format(self._device_id)
  189. )
  190. if not os.path.isfile(op_detail_file_path):
  191. logger.warning('The file <%s> does not exist.', op_detail_file_path)
  192. return
  193. if not os.path.isfile(framework_file_path):
  194. logger.warning('The file <%s> does not exist.', framework_file_path)
  195. return
  196. framework_infos = dict()
  197. with open(framework_file_path, 'r') as file:
  198. csv_reader = csv.reader(file)
  199. _ = next(csv_reader)
  200. for info in csv_reader:
  201. framework_infos[info[3]] = [
  202. info[3], info[4], info[5], info[6], json.loads(info[7]) if info[7] else None]
  203. with open(op_detail_file_path, 'r') as file:
  204. csv_reader = csv.reader(file)
  205. _ = next(csv_reader)
  206. for info in csv_reader:
  207. framework_info = framework_infos.get(info[0])
  208. self._aicore_detail_data.append(
  209. [
  210. framework_info[1], framework_info[2], float(info[1]),
  211. framework_info[3], framework_info[0], framework_info[4]
  212. ]
  213. )
  214. del framework_infos
  215. def _aicore_trace_data_load(self):
  216. """Load data according to the parsed AICORE operator types file."""
  217. file_path = query_latest_trace_time_file(self._profiling_dir, int(self._device_id))
  218. if not file_path:
  219. logger.error("Failed to find parsed trace time file.")
  220. raise ProfilerFileNotFoundException('parsed step trace time file')
  221. with open(file_path, 'r') as handle:
  222. csv_reader = csv.reader(handle)
  223. self.__column__ = next(csv_reader)
  224. self._aicore_trace_data = list(csv_reader)
  225. self._size = len(self._aicore_trace_data) - 1
  226. self._load_point_info()
  227. def _load_point_info(self):
  228. """Load point info."""
  229. file_path = os.path.join(self._profiling_dir, 'step_trace_point_info.json')
  230. if os.path.isfile(file_path):
  231. with open(file_path, 'r', encoding='utf-8') as file:
  232. try:
  233. self._point_info = json.load(file)
  234. except (json.JSONDecodeError, TypeError) as err:
  235. logger.warning(err)
  236. raise ProfilerRawFileException('Fail to parse point info file.')
  237. def _query_for_all_reduce(self):
  238. """
  239. Query for all reduce info.
  240. Returns:
  241. list[dict], reduce information. Each item is the reduce info for one step.
  242. The reduce info is format like:
  243. {stream_id: List[Tuple(start_point, end_point, duration, field_name)]}.
  244. """
  245. self._aicore_trace_data_load()
  246. reduce_infos = []
  247. for row_info in self._aicore_trace_data[:-1]:
  248. row_info_dict = self._get_info_dict_from_row_data(row_info, 'systime')
  249. reduce_info = self._sort_reduce_by_time(row_info_dict)
  250. if reduce_info:
  251. reduce_infos.extend(reduce_info)
  252. return reduce_infos
  253. def _get_info_dict_from_row_data(self, row_info, time_type):
  254. """
  255. Get step info in dict format.
  256. Args:
  257. row_info (list[str]): Step info, the value is corresponding to `__column__`.
  258. time_type (str): The value type. `systime` keeps the original value.
  259. `realtime` transforms the value in millisecond. Default: `realtime`.
  260. Returns:
  261. dict, step trace information. The key is in `__column__`.
  262. """
  263. row_info_dict = {}
  264. for key, value in zip(self.__column__, row_info):
  265. if key == 'step_num':
  266. continue
  267. value = to_int(value, key)
  268. row_info_dict[key] = to_millisecond(value) if time_type == 'realtime' else value
  269. return row_info_dict
  270. def _sort_reduce_by_time(self, row_info_dict):
  271. """
  272. Sort reduce info by time.
  273. Args:
  274. row_info_dict (dict): Step trace information.
  275. Returns:
  276. list, including the all reduce info sorted by start time only.
  277. [
  278. [reduce_field, stream_id, reduce_start, reduce_duration],
  279. [...],
  280. [...]
  281. ]
  282. """
  283. factor = 1e5 # convert time unit from 10ns to 1ms
  284. reduce_pid = 10000
  285. reduce_info = []
  286. reduce_fields = [field_name for field_name in self.__column__
  287. if field_name.startswith('stream_') and not field_name.endswith('point')]
  288. for reduce_field in reduce_fields:
  289. reduce_start = row_info_dict.get(reduce_field + '_start_point')
  290. reduce_start = reduce_start / factor \
  291. if reduce_start else 0
  292. reduce_duration = row_info_dict.get(reduce_field)
  293. reduce_duration = reduce_duration / factor if reduce_duration else 0
  294. if not (reduce_start and reduce_duration):
  295. logger.info("Reduce event missing value.")
  296. continue
  297. cur_stream_id = reduce_field.split('_', 2)[1]
  298. reduce_meta = [reduce_field, int(cur_stream_id), reduce_start,
  299. reduce_duration, reduce_pid]
  300. reduce_info.append(reduce_meta)
  301. return reduce_info
  302. def _query_and_sort_by_op_type(self, filter_condition, op_type_order: list):
  303. """
  304. Query the AICORE operator detail information by `filter_condition`,
  305. and sort by `op_type_order` and execution time.
  306. Args:
  307. filter_condition (dict): The filter condition.
  308. op_type_order (list[str]): The name of the operator type in order.
  309. Returns:
  310. dict, The results are filtered and sorted.
  311. """
  312. self._aicore_detail_data_load()
  313. if filter_condition is None:
  314. filter_condition = {}
  315. self._filter(filter_condition)
  316. type_detail_cache = {}
  317. for detail_info in self._result:
  318. op_type = detail_info[1]
  319. if op_type not in op_type_order:
  320. continue
  321. infos = type_detail_cache.get(op_type)
  322. if infos:
  323. infos.append(detail_info)
  324. else:
  325. type_detail_cache[op_type] = [detail_info]
  326. result = []
  327. for op_type in op_type_order:
  328. detail_infos = type_detail_cache.get(op_type)
  329. if detail_infos is None:
  330. continue
  331. detail_infos.sort(key=lambda item: item[2], reverse=True)
  332. result.extend(detail_infos)
  333. return {
  334. 'col_name_detail': self._display_col_names_detail,
  335. 'object': result
  336. }
  337. def _filter(self, filter_condition):
  338. """
  339. Filter the profiling data according to the filter condition.
  340. Args:
  341. filter_condition (dict): The filter condition.
  342. """
  343. def _inner_filter(item: list):
  344. return self._default_filter(item, filter_condition)
  345. def _inner_map(item: list):
  346. inner_item = item[0:4]
  347. if is_display_full_op_name:
  348. inner_item.append(item[4])
  349. if is_display_detail:
  350. inner_item.append(item[5])
  351. return inner_item
  352. is_display_detail = filter_condition.get('is_display_detail', True)
  353. is_display_full_op_name = filter_condition.get(
  354. 'is_display_full_op_name', True
  355. )
  356. self._set_display_col_name(is_display_detail, is_display_full_op_name)
  357. if is_display_detail and is_display_full_op_name:
  358. self._result = list(filter(_inner_filter, self._aicore_detail_data))
  359. else:
  360. self._result = list(
  361. map(_inner_map, filter(_inner_filter, self._aicore_detail_data))
  362. )
  363. def _default_filter(self, item, condition):
  364. """
  365. The default filter method.
  366. Args:
  367. item (list[Union[str, float, int]]): A piece of data to be filtered.
  368. condition (dict): The filter condition.
  369. Returns:
  370. bool, `True` if the item is satisfied.
  371. """
  372. for condition_key, condition_value in condition.items():
  373. if condition_key in self._none_filter_condition_key:
  374. continue
  375. if condition_key in self._col_names_detail:
  376. index = self._col_names_detail.index(condition_key)
  377. actual_value = item[index]
  378. for exp_key, exp_value in condition_value.items():
  379. if not self._is_match_condition(
  380. exp_key, exp_value, actual_value):
  381. return False
  382. return True
  383. def _is_match_condition(self, exp_key, exp_value, actual_value):
  384. """
  385. Check whether the actual value meets the expect condition.
  386. Args:
  387. exp_key (str): Expect key of the condition.
  388. exp_value (str): Expect value.
  389. actual_value (str): Actual value.
  390. Returns:
  391. bool, `True` if the actual meets the expect condition, else `False`.
  392. """
  393. if exp_key == 'in':
  394. if actual_value not in exp_value:
  395. return False
  396. elif exp_key == 'not_in':
  397. if actual_value in exp_value:
  398. return False
  399. elif exp_key == 'partial_match_str_in':
  400. for partial_match_str in exp_value:
  401. if partial_match_str in actual_value:
  402. return True
  403. return False
  404. else:
  405. return False
  406. return True
  407. def _set_display_col_name(self, is_display_detail, is_display_full_op_name):
  408. """
  409. Set the display column name according to the filter condition.
  410. Args:
  411. is_display_detail (bool): Whether to display the detailed operator
  412. information.
  413. is_display_full_op_name (bool): Whether to display the operator full
  414. name.
  415. """
  416. self._display_col_names_detail = self._col_names_detail[0:4]
  417. if is_display_full_op_name:
  418. self._display_col_names_detail.append(self._col_names_detail[4])
  419. if is_display_detail:
  420. self._display_col_names_detail.append(self._col_names_detail[5])
  421. class TimelineAnalyser:
  422. """
  423. Analyse timeline data from file.
  424. """
  425. __col_names__ = ['op_name', 'stream_id', 'start_time', 'duration']
  426. _output_timeline_data_file_path = 'output_timeline_data_{}.txt'
  427. _min_cycle_counter_file_path = 'min_cycle_counter_{}.txt'
  428. _display_filename = 'timeline_display_{}.json'
  429. _timeline_summary_filename = 'timeline_summary_{}.json'
  430. _timeline_meta = []
  431. _timeline_summary = {
  432. 'total_time': 0,
  433. 'num_of_streams': 0,
  434. 'num_of_ops': 0,
  435. 'op_exe_times': 0
  436. }
  437. def __init__(self, profiling_dir, device_id):
  438. self._profiling_dir = profiling_dir
  439. self._device_id = device_id
  440. def write_timeline(self):
  441. """Load data according to the parsed profiling files."""
  442. # Write timeline to file.
  443. logger.info('Writing timeline file...')
  444. self.write_timeline_to_json_by_limitation()
  445. logger.info('Finished file writing!')
  446. def write_timeline_to_json_by_limitation(self):
  447. """Write timeline to json by limitation."""
  448. display_filename = self._display_filename.format(self._device_id)
  449. display_file_path = os.path.join(
  450. self._profiling_dir,
  451. display_filename
  452. )
  453. display_file_path = validate_and_normalize_path(display_file_path)
  454. length = len(self._timeline_meta)
  455. try:
  456. with open(display_file_path, 'w') as json_file:
  457. json_file.write('[')
  458. for index, item in enumerate(self._timeline_meta):
  459. json.dump(item, json_file)
  460. file_size = os.path.getsize(display_file_path)
  461. if file_size > SIZE_LIMIT:
  462. break
  463. if index == length - 1:
  464. break
  465. json_file.write(',')
  466. json_file.write(']')
  467. except (IOError, OSError) as err:
  468. logger.error('Error occurred when write timeline display file: %s', err)
  469. raise ProfilerIOException
  470. def write_timeline_summary(self):
  471. """Write timeline summary to json."""
  472. timeline_summary_file_path = os.path.join(
  473. self._profiling_dir,
  474. self._timeline_summary_filename.format(self._device_id)
  475. )
  476. timeline_summary_file_path = validate_and_normalize_path(timeline_summary_file_path)
  477. try:
  478. with open(timeline_summary_file_path, 'w') as json_file:
  479. json.dump(self._timeline_summary, json_file)
  480. except (IOError, OSError) as err:
  481. logger.error('Error occurred when write timeline summary file: %s', err)
  482. raise ProfilerIOException
  483. def _load_timeline_data(self):
  484. """Load timeline data from file."""
  485. file_path = os.path.join(
  486. self._profiling_dir,
  487. self._output_timeline_data_file_path.format(self._device_id)
  488. )
  489. file_path = validate_and_normalize_path(file_path)
  490. if not os.path.exists(file_path):
  491. logger.error("Failed to find parsed timeline file.")
  492. raise ProfilerFileNotFoundException('parsed timeline file')
  493. timeline_list = []
  494. try:
  495. with open(file_path, 'r') as f_obj:
  496. for line in f_obj:
  497. if not line.startswith('op_name'):
  498. line_list = line.strip('\n').split(',')
  499. timeline_list.append(line_list)
  500. except (IOError, OSError) as err:
  501. logger.error('Error occurred when read timeline intermediate file: %s', err)
  502. raise ProfilerIOException
  503. return timeline_list
  504. def _parse_timeline_data(self, timeline, min_cycle_counter):
  505. """Parse timeline data."""
  506. # factor to convert the time unit from 1ms to 1us for timeline display
  507. factor = 1000
  508. op_meta = TimelineContainer(timeline)
  509. timeline_dict = {}
  510. timeline_dict['name'] = op_meta.op_name
  511. timeline_dict['ph'] = 'X'
  512. timeline_dict['tid'] = op_meta.stream_id
  513. timeline_dict['ts'] = (op_meta.start_time - min_cycle_counter) * factor
  514. dur = op_meta.duration * factor
  515. timeline_dict['dur'] = dur
  516. if op_meta.pid is None:
  517. timeline_dict['pid'] = int(self._device_id)
  518. # Update total time of operator execution.
  519. self._timeline_summary['total_time'] += dur
  520. else: # AllReduce and AI CPU pid
  521. timeline_dict['pid'] = op_meta.pid
  522. self._timeline_meta.append(timeline_dict)
  523. @staticmethod
  524. def _update_num_of_streams(timeline, stream_count_dict):
  525. """Update number of streams."""
  526. stream_id = timeline[1]
  527. if stream_id not in stream_count_dict.keys():
  528. stream_count_dict[stream_id] = 1
  529. else:
  530. stream_count_dict[stream_id] += 1
  531. def get_min_cycle_counter(self):
  532. """
  533. Get minimum cycle counter.
  534. Returns:
  535. float, the minimum value of the cycle counter.
  536. """
  537. file_path = os.path.join(
  538. self._profiling_dir,
  539. self._min_cycle_counter_file_path.format(self._device_id)
  540. )
  541. file_path = validate_and_normalize_path(file_path)
  542. if os.path.exists(file_path):
  543. try:
  544. with open(file_path, 'r') as f_obj:
  545. min_cycle_counter = f_obj.read()
  546. min_cycle_counter = float(min_cycle_counter) \
  547. if not min_cycle_counter == 'inf' else 0
  548. except (IOError, OSError) as err:
  549. logger.error('Error occurred when read minimum cycle counter: %s', err)
  550. raise ProfilerIOException
  551. else:
  552. min_cycle_counter = 0
  553. logger.info("No min cycle counter recorded.")
  554. return min_cycle_counter
  555. def init_timeline(self, all_reduce_info, framework_info, aicpu_info, min_cycle_counter):
  556. """
  557. Init timeline metadata, adding all collected info.
  558. Args:
  559. all_reduce_info (list[list]): The metadata of AllReduce operator.
  560. framework_info (dict): The framework metadata.
  561. aicpu_info (dict): The metadata of AI CPU operator.
  562. min_cycle_counter (float): The minimum cycle counter of the timeline.
  563. """
  564. if min_cycle_counter == float('inf'):
  565. min_cycle_counter = 0
  566. logger.info('Initiating timeline...')
  567. timeline_list = self._load_timeline_data()
  568. self._timeline_summary['op_exe_times'] = len(timeline_list)
  569. # Add AllReduce info to timeline temp list and sort by start time.
  570. if all_reduce_info:
  571. logger.debug('AllReduce info found. Start adding info into timeline...')
  572. timeline_list.extend(all_reduce_info)
  573. timeline_list.sort(key=lambda x: float(x[2]))
  574. # Add AI CPU data into timeline temp list and sort by start time.
  575. aicpu_data = aicpu_info.get('info')
  576. if aicpu_data:
  577. timeline_list.extend(aicpu_data)
  578. timeline_list.sort(key=lambda x: float(x[2]))
  579. self._timeline_summary['op_exe_times'] += aicpu_info.get('op_exe_times', 0)
  580. self._timeline_summary['num_of_streams'] += aicpu_info.get('num_of_streams', 0)
  581. self._timeline_summary['num_of_ops'] += aicpu_info.get('num_of_ops', 0)
  582. self._timeline_summary['total_time'] += aicpu_info.get('total_time', 0)
  583. # Init a dict for counting the num of streams.
  584. stream_count_dict = {}
  585. for timeline in timeline_list:
  586. self._parse_timeline_data(timeline, min_cycle_counter)
  587. # Updating the collection of streams.
  588. if len(timeline) == 4:
  589. self._update_num_of_streams(timeline, stream_count_dict)
  590. # Get framework metadata.
  591. framework_obj_list = framework_info.get('object')
  592. # The length of list is the number of operators.
  593. self._timeline_summary['num_of_ops'] += len(framework_obj_list)
  594. self._add_framework_info(framework_obj_list)
  595. logger.info('Finished adding info into timeline...')
  596. # Update timeline summary info
  597. self._timeline_summary['num_of_streams'] += len(stream_count_dict.keys())
  598. def _add_framework_info(self, framework_obj_list):
  599. """
  600. Add framework info into timeline metadata.
  601. Args:
  602. framework_obj_list (list): The framework metadata.
  603. """
  604. logger.debug('Start adding framework info into timeline...')
  605. # Get the framework info that will be written into timeline.
  606. framework_info_dict = {}
  607. for framework_obj in framework_obj_list:
  608. op_name = framework_obj[0]
  609. op_type = framework_obj[1]
  610. op_full_name = framework_obj[4]
  611. op_info = framework_obj[5]
  612. framework_info_dict[op_full_name] = {
  613. 'name': op_name,
  614. 'args': {
  615. 'type': op_type,
  616. 'fullname': op_full_name
  617. }
  618. }
  619. framework_info_dict[op_full_name]['args'].update(op_info)
  620. # Insert framework info into timeline.
  621. for timeline_item in self._timeline_meta:
  622. op_full_name = timeline_item.get('name')
  623. framework_item = framework_info_dict.get(op_full_name)
  624. if framework_item:
  625. timeline_item['name'] = framework_item.get('name')
  626. timeline_item['args'] = framework_item.get('args')
  627. logger.debug('Finished adding framework info into timeline...')