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

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