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.

framework_parser.py 21 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. """Thr parser for parsing framework files."""
  16. import csv
  17. import enum
  18. import json
  19. import os
  20. import re
  21. from mindspore.profiler.common.exceptions.exceptions import \
  22. ProfilerPathErrorException, ProfilerDirNotFoundException, \
  23. ProfilerFileNotFoundException, ProfilerDeviceIdMismatchException, \
  24. ProfilerRawFileException, ProfilerParamValueErrorException
  25. from mindspore.profiler.common.validator.validate_path import \
  26. validate_and_normalize_path
  27. class VmDataType(enum.IntEnum):
  28. """Definition of vm data type."""
  29. NUMBER_TYPE_BEGIN = 26
  30. NUMBER_TYPE_BOOL = 27
  31. NUMBER_TYPE_INT = 28
  32. NUMBER_TYPE_INT8 = 29
  33. NUMBER_TYPE_INT16 = 30
  34. NUMBER_TYPE_INT32 = 31
  35. NUMBER_TYPE_INT64 = 32
  36. NUMBER_TYPE_UINT = 33
  37. NUMBER_TYPE_UINT8 = 34
  38. NUMBER_TYPE_UINT16 = 35
  39. NUMBER_TYPE_UINT32 = 36
  40. NUMBER_TYPE_UINT64 = 37
  41. NUMBER_TYPE_FLOAT = 38
  42. NUMBER_TYPE_FLOAT16 = 39
  43. NUMBER_TYPE_FLOAT32 = 40
  44. NUMBER_TYPE_FLOAT64 = 41
  45. NUMBER_TYPE_END = 42
  46. @classmethod
  47. def get_data_type_name(cls, num):
  48. """
  49. Get the name of data type by enum number.
  50. Args:
  51. num (int): Enum number.
  52. Returns:
  53. str, the name of data type.
  54. """
  55. data_type = cls._value2member_map_.get(num)
  56. return 'UNKNOWN' if data_type is None else data_type.name
  57. class GeDataType(enum.IntEnum):
  58. """Definition of ge data type."""
  59. DT_FLOAT = 0
  60. DT_FLOAT16 = 1
  61. DT_INT8 = 2
  62. DT_INT16 = 6
  63. DT_UINT16 = 7
  64. DT_UINT8 = 4
  65. DT_INT32 = 3
  66. DT_INT64 = 9
  67. DT_UINT32 = 8
  68. DT_UINT64 = 10
  69. DT_BOOL = 12
  70. DT_DOUBLE = 11
  71. DT_STRING = 13
  72. DT_DUAL_SUB_INT8 = 14
  73. DT_DUAL_SUB_UINT8 = 15
  74. DT_COMPLEX64 = 16
  75. DT_COMPLEX128 = 17
  76. DT_QINT8 = 18
  77. DT_QINT16 = 19
  78. DT_QINT32 = 20
  79. DT_QUINT8 = 21
  80. DT_QUINT16 = 22
  81. DT_RESOURCE = 23
  82. DT_STRING_REF = 24
  83. DT_DUAL = 25
  84. DT_UNDEFINED = 26
  85. @classmethod
  86. def get_data_type_name(cls, num):
  87. """
  88. Get the name of data type by enum number.
  89. Args:
  90. num (int): Enum number.
  91. Returns:
  92. str, the name of data type.
  93. """
  94. data_type = cls._value2member_map_.get(num)
  95. return 'UNKNOWN' if data_type is None else data_type.name
  96. class GeFormat(enum.IntEnum):
  97. """Definition of ge format type."""
  98. FORMAT_NCHW = 0
  99. FORMAT_NHWC = 1
  100. FORMAT_ND = 2
  101. FORMAT_NC1HWC0 = 3
  102. FORMAT_FRACTAL_Z = 4
  103. FORMAT_NC1C0HWPAD = 5
  104. FORMAT_NHWC1C0 = 6
  105. FORMAT_FSR_NCHW = 7
  106. FORMAT_FRACTAL_DECONV = 8
  107. FORMAT_C1HWNC0 = 9
  108. FORMAT_FRACTAL_DECONV_TRANSPOSE = 10
  109. FORMAT_FRACTAL_DECONV_SP_STRIDE_TRANS = 11
  110. FORMAT_NC1HWC0_C04 = 12
  111. FORMAT_FRACTAL_Z_C04 = 13
  112. FORMAT_CHWN = 14
  113. FORMAT_FRACTAL_DECONV_SP_STRIDE8_TRANS = 15
  114. FORMAT_HWCN = 16
  115. FORMAT_NC1KHKWHWC0 = 17
  116. FORMAT_BN_WEIGHT = 18
  117. FORMAT_FILTER_HWCK = 19
  118. FORMAT_HASHTABLE_LOOKUP_LOOKUPS = 20
  119. FORMAT_HASHTABLE_LOOKUP_KEYS = 21
  120. FORMAT_HASHTABLE_LOOKUP_VALUE = 22
  121. FORMAT_HASHTABLE_LOOKUP_OUTPUT = 23
  122. FORMAT_HASHTABLE_LOOKUP_HITS = 24
  123. FORMAT_C1HWNCOC0 = 25
  124. FORMAT_MD = 26
  125. FORMAT_NDHWC = 27
  126. FORMAT_FRACTAL_ZZ = 28
  127. FORMAT_FRACTAL_NZ = 29
  128. FORMAT_NCDHW = 30
  129. FORMAT_DHWCN = 31
  130. FORMAT_NDC1HWC0 = 32
  131. FORMAT_FRACTAL_Z_3D = 33
  132. FORMAT_CN = 34
  133. FORMAT_NC = 35
  134. FORMAT_DHWNC = 36
  135. FORMAT_FRACTAL_Z_3D_TRANSPOSE = 37
  136. FORMAT_RESERVED = 38
  137. FORMAT_ALL = 39
  138. @classmethod
  139. def get_format_name(cls, num):
  140. """
  141. Get the name of format type by enum number.
  142. Args:
  143. num (int): Enum number.
  144. Returns:
  145. str, the name of format type.
  146. """
  147. format_type = cls._value2member_map_.get(num)
  148. return 'UNKNOWN' if format_type is None else format_type.name
  149. class FrameworkParser:
  150. """
  151. Thr parser for parsing framework files.
  152. Args:
  153. profiling_id (str): The profiling ID.
  154. device_id (str): The device ID.
  155. output_path (str): The directory of the parsed file. Default: `./`.
  156. """
  157. _raw_data_dir = '/var/log/npu/profiling'
  158. _regex_framework = r'Framework\.host\.(?P<data_type>.+)\.(?P<device_id>\d).+'
  159. _regex_framework_in_data = r'Framework\.host\.(?P<data_type>.+)\.' \
  160. r'(?P<device_id>\d)\.(?P<profiling_id>[a-zA-Z0-9]+).+'
  161. _col_names = [
  162. 'task_id', 'stream_id', 'block_dim', 'full_op_name', 'op_name',
  163. 'op_type', 'subgraph', 'op_info'
  164. ]
  165. _graph_attr_name = [
  166. 'input_format', 'input_data_type', 'input_shape', 'output_format',
  167. 'output_data_type', 'output_shape'
  168. ]
  169. # if the task id is less than the task id threshold, The combination of
  170. # task id and Stream id represents one operator, else the task id represents
  171. # one operator
  172. _task_id_threshold = 25000
  173. def __init__(self, profiling_id, device_id, output_path='./'):
  174. self._profiling_path = self._get_raw_profiling_path(profiling_id)
  175. self._backend_type = None
  176. self._framework_path = {'graph': [], 'task': [], 'point': []}
  177. self._search_file(profiling_id, device_id)
  178. self._device_id = device_id
  179. self._save_path = self._get_save_path(device_id, output_path)
  180. self._task_id_full_op_name_dict = {}
  181. self._task_cache = {}
  182. self._point_info = {}
  183. self._parse_task_files()
  184. self._parse_point_files()
  185. @property
  186. def save_path(self):
  187. """
  188. The property of save path.
  189. Returns:
  190. str, the save path.
  191. """
  192. return self._save_path
  193. @property
  194. def point_info(self):
  195. """
  196. The property of the framework point information.
  197. Returns:
  198. dict, the framework point information.
  199. """
  200. return self._point_info
  201. def to_task_id_full_op_name_dict(self):
  202. """
  203. Get the task id and full operator name dict.
  204. Returns:
  205. dict, the task id and full operator name dict.
  206. """
  207. return self._task_id_full_op_name_dict
  208. def parse(self):
  209. """Parse the framework files."""
  210. self._parse_graph_files_and_save(self._task_cache)
  211. del self._task_cache
  212. def check_op_name(self, op_name, is_prefix=True):
  213. """
  214. Check whether the operator name exists.
  215. Args:
  216. op_name (str): The operator name or operator name prefix.
  217. is_prefix (bool): `True` if the op_name is prefix, else `False`.
  218. Default: True.
  219. Returns:
  220. bool, `True` if the operator name does exist in framework file, else
  221. `False`.
  222. """
  223. if not op_name:
  224. raise ProfilerParamValueErrorException('The op_name should exist.')
  225. for full_op_name in self._task_id_full_op_name_dict.values():
  226. if full_op_name:
  227. if is_prefix and full_op_name.startswith(op_name):
  228. return True
  229. if not is_prefix and op_name == full_op_name:
  230. return True
  231. return False
  232. def _get_raw_profiling_path(self, profiling_id):
  233. """
  234. Get raw profiling path.
  235. Args:
  236. profiling_id (str): The profiling ID.
  237. Returns:
  238. str, the raw profiling path.
  239. Raises:
  240. ProfilerPathErrorException: If the profiling path is invalid.
  241. ProfilerDirNotFoundException: If the profiling dir is not found.
  242. """
  243. profiling_path = os.path.join(self._raw_data_dir, profiling_id)
  244. try:
  245. profiling_path = validate_and_normalize_path(profiling_path)
  246. except RuntimeError:
  247. raise ProfilerPathErrorException('Profiling path is invalid.')
  248. if not os.path.isdir(profiling_path):
  249. raise ProfilerDirNotFoundException(profiling_path)
  250. return profiling_path
  251. def _search_file(self, profiling_id, device_id):
  252. """
  253. Search all framework files in raw profiling path.
  254. Args:
  255. profiling_id (str): The profiling ID.
  256. device_id (str): The device ID.
  257. Raises:
  258. ProfilerFileNotFoundException: If the framework files are not found.
  259. """
  260. # first search in the JOB dir, and if not, search in the sub directory
  261. # in the JOB
  262. self._search_file_from_job_path(device_id, search_in_sub_path=False)
  263. if self._backend_type is None:
  264. self._search_file_from_job_path(device_id, search_in_sub_path=True)
  265. self._search_file_from_data_path(profiling_id, device_id)
  266. if self._backend_type is None:
  267. raise ProfilerFileNotFoundException('Framework')
  268. self._framework_path['graph'].sort()
  269. self._framework_path['task'].sort()
  270. def _search_file_from_job_path(self, device_id, search_in_sub_path=False):
  271. """
  272. Search framework files from job path.
  273. Args:
  274. device_id (str): The device ID.
  275. search_in_sub_path (bool): `True` if search file in profiling dir,
  276. else search in profiling sub dir. Default: False.
  277. Raises:
  278. ProfilerRawFileException: If the framework file type is inconsistent.
  279. ProfilerDeviceIdMismatchException: If the device id is mismatch
  280. with framework in the raw dir.
  281. """
  282. profiling_dir = os.path.join(self._profiling_path, 'data') \
  283. if search_in_sub_path else self._profiling_path
  284. if not os.path.isdir(profiling_dir):
  285. return
  286. files = os.listdir(profiling_dir)
  287. for file in files:
  288. pattern = re.search(self._regex_framework, file)
  289. if not pattern or file.endswith('.done'):
  290. continue
  291. attrs = pattern.groupdict()
  292. device_id_in_path = attrs.get('device_id')
  293. if device_id_in_path != device_id:
  294. raise ProfilerDeviceIdMismatchException()
  295. data_type = attrs.get('data_type')
  296. if data_type.startswith('vm.'):
  297. if self._backend_type and self._backend_type != 'vm':
  298. raise ProfilerRawFileException('Backend type is inconsistent.')
  299. self._backend_type = 'vm'
  300. data_type = data_type.split('.')[1]
  301. else:
  302. if self._backend_type and self._backend_type != 'ge':
  303. raise ProfilerRawFileException('Backend type is inconsistent.')
  304. self._backend_type = 'ge'
  305. if data_type.startswith('graph_desc_info'):
  306. self._framework_path['graph'].append(
  307. os.path.join(profiling_dir, file)
  308. )
  309. elif data_type.startswith('task_desc_info'):
  310. self._framework_path['task'].append(
  311. os.path.join(profiling_dir, file)
  312. )
  313. elif data_type.startswith('point'):
  314. self._framework_path['point'].append(
  315. os.path.join(profiling_dir, file)
  316. )
  317. def _search_file_from_data_path(self, profiling_id, device_id):
  318. """
  319. Search framework files from data path.
  320. Args:
  321. profiling_id (str): The profiling ID.
  322. device_id (str): The device ID.
  323. Raises:
  324. ProfilerRawFileException: If the framework file type is inconsistent.
  325. ProfilerDeviceIdMismatchException: If the device id is mismatch
  326. with framework in the raw dir.
  327. """
  328. profiling_data_path = os.path.join(
  329. self._raw_data_dir, 'container', device_id, 'data'
  330. )
  331. if not os.path.isdir(profiling_data_path):
  332. return
  333. files = os.listdir(profiling_data_path)
  334. for file in files:
  335. pattern = re.search(self._regex_framework_in_data, file)
  336. if not pattern or file.endswith('.done') or file.endswith('.zip'):
  337. continue
  338. attrs = pattern.groupdict()
  339. profiling_id_in_path = attrs.get('profiling_id')
  340. if profiling_id_in_path != profiling_id:
  341. continue
  342. device_id_in_path = attrs.get('device_id')
  343. if device_id_in_path != device_id:
  344. raise ProfilerDeviceIdMismatchException()
  345. data_type = attrs.get('data_type')
  346. if data_type.startswith('vm.'):
  347. if self._backend_type and self._backend_type != 'vm':
  348. raise ProfilerRawFileException('Backend type is inconsistent.')
  349. self._backend_type = 'vm'
  350. data_type = data_type.split('.')[1]
  351. else:
  352. if self._backend_type and self._backend_type != 'ge':
  353. raise ProfilerRawFileException('Backend type is inconsistent.')
  354. self._backend_type = 'ge'
  355. if data_type.startswith('graph_desc_info'):
  356. self._framework_path['graph'].append(
  357. os.path.join(profiling_data_path, file)
  358. )
  359. elif data_type.startswith('task_desc_info'):
  360. self._framework_path['task'].append(
  361. os.path.join(profiling_data_path, file)
  362. )
  363. elif data_type.startswith('point'):
  364. self._framework_path['point'].append(
  365. os.path.join(profiling_data_path, file)
  366. )
  367. def _get_save_path(self, device_id, output_path):
  368. """
  369. Get the save path.
  370. Args:
  371. device_id (str): The device ID.
  372. output_path (str): The output dir.
  373. Returns:
  374. str, the save path.
  375. Raises:
  376. ProfilerPathErrorException: If the output path is invalid.
  377. ProfilerDirNotFoundException: If the output dir is not found.
  378. """
  379. try:
  380. output_dir = validate_and_normalize_path(output_path)
  381. except RuntimeError:
  382. raise ProfilerPathErrorException('Output path is invalid.')
  383. if not os.path.isdir(output_dir):
  384. raise ProfilerDirNotFoundException(output_dir)
  385. return os.path.join(
  386. output_dir, '_'.join(['framework', 'raw', device_id]) + '.csv'
  387. )
  388. def _parse_task_files(self):
  389. """Parse the framework task files."""
  390. for path in self._framework_path['task']:
  391. with open(path, 'r') as file:
  392. for task_info in file:
  393. infos = task_info.strip('\n').split(' ')
  394. infos = infos[1:] if len(infos) == 5 else infos
  395. # key is op name, values is task id, stream id, block_dim
  396. self._task_cache[infos[0]] = [infos[2], infos[3], infos[1]]
  397. # if the task id is less than the task id threshold, the
  398. # stream id and task id correspond to an operator
  399. task_id = infos[2]
  400. if int(task_id) < self._task_id_threshold:
  401. task_id = '_'.join([infos[3], task_id])
  402. self._task_id_full_op_name_dict[task_id] = infos[0]
  403. def _parse_graph_files_and_save(self, task_cache):
  404. """
  405. Parse the framework graph files and save the framework information.
  406. Args:
  407. task_cache (dict): The task information cache.
  408. """
  409. with open(self._save_path, 'w') as save_file:
  410. csv_writer = csv.writer(save_file)
  411. csv_writer.writerow(self._col_names)
  412. for path in self._framework_path['graph']:
  413. with open(path, 'r') as graph_file:
  414. for graph_info in graph_file:
  415. result = self._parse_one_row_graph_info(graph_info)
  416. task_info = task_cache.get(result[0])
  417. if task_info:
  418. task_info.extend(result)
  419. csv_writer.writerow(task_info)
  420. del task_cache[result[0]]
  421. else:
  422. save_info = [None, None, None]
  423. save_info.extend(result)
  424. csv_writer.writerow(save_info)
  425. none_list = [None, None, None, None]
  426. for key, value in task_cache.items():
  427. value.append(key)
  428. value.extend(none_list)
  429. csv_writer.writerow(value)
  430. def _parse_one_row_graph_info(self, row_info):
  431. """
  432. Parse the graph information in one row.
  433. Args:
  434. row_info (str): One row graph information.
  435. Returns:
  436. list[str], the parsed graph information.
  437. """
  438. full_op_name = None
  439. op_name = None
  440. subgraph_name = None
  441. op_type = None
  442. op_info = dict()
  443. cur_op_info_key = None
  444. infos = row_info.strip('\n').split(' ')
  445. for info in infos:
  446. attr_name, attr_value = info.split(':', 1)
  447. if attr_name == 'op_name':
  448. full_op_name = attr_value
  449. subgraph_name = self._get_subgraph_name(full_op_name)
  450. op_name = self._get_op_name(full_op_name, subgraph_name)
  451. elif attr_name == 'op_type':
  452. op_type = attr_value
  453. elif attr_name in ['input_id', 'output_id']:
  454. cur_op_info_key = '{}_{}'.format(
  455. attr_name.split('_')[0], attr_value
  456. )
  457. op_info[cur_op_info_key] = dict()
  458. elif attr_name in self._graph_attr_name:
  459. op_attr = attr_name.split('_', 1)[1]
  460. if op_attr == 'shape':
  461. attr_value = attr_value.strip('"')
  462. if self._backend_type == 'vm':
  463. if op_attr == 'data_type':
  464. attr_value = VmDataType.get_data_type_name(
  465. int(attr_value)
  466. )
  467. else:
  468. if op_attr == 'data_type':
  469. attr_value = GeDataType.get_data_type_name(
  470. int(attr_value)
  471. )
  472. elif op_attr == 'format':
  473. attr_value = GeFormat.get_format_name(int(attr_value))
  474. op_info[cur_op_info_key][op_attr] = attr_value
  475. # the list info are full_op_name, op_name, op_type, subgraph, op_info
  476. return [full_op_name, op_name, op_type, subgraph_name,
  477. json.dumps(op_info)]
  478. def _get_subgraph_name(self, full_op_name):
  479. """
  480. Get subgraph name.
  481. Args:
  482. full_op_name (str): The full operator name.
  483. Returns:
  484. str, the subgraph name.
  485. """
  486. subgraph_name = full_op_name.split('/', 1)[0]
  487. if subgraph_name in ['Default', 'Gradients']:
  488. return subgraph_name
  489. return None
  490. def _get_op_name(self, full_op_name, subgraph_name):
  491. """
  492. Get operator name.
  493. Args:
  494. full_op_name (str): The full operator name.
  495. subgraph_name (str): The subgraph name.
  496. Returns:
  497. str, the operator name.
  498. """
  499. if subgraph_name is None:
  500. return full_op_name
  501. if self._backend_type == 'vm':
  502. return full_op_name.split('/')[-1]
  503. strs = full_op_name.split(subgraph_name + '/')
  504. op_name = None
  505. for name_str in strs:
  506. if not name_str:
  507. continue
  508. if op_name is None:
  509. op_name = name_str.split('/')[-1]
  510. else:
  511. op_name = '+'.join([op_name, name_str.split('/')[-1]])
  512. return op_name
  513. def _parse_point_files(self):
  514. """Parse the framework point files."""
  515. for path in self._framework_path['point']:
  516. with open(path, 'r') as file:
  517. for point_info in file:
  518. infos = point_info.strip('\n').split(' ')
  519. self._point_info[int(infos[0])] = infos[1]