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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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 marshmallow import ValidationError
  22. from mindinsight.profiler.common.exceptions.exceptions import \
  23. ProfilerPathErrorException, ProfilerDirNotFoundException, \
  24. ProfilerFileNotFoundException, ProfilerDeviceIdMismatchException, \
  25. ProfilerRawFileException, ProfilerParamValueErrorException
  26. from mindinsight.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\.host\.(?P<data_type>.+)\.(?P<device_id>\d).+'
  160. _regex_framework_in_data = r'Framework\.host\.(?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(
  247. profiling_path, 'profiler'
  248. )
  249. except ValidationError:
  250. raise ProfilerPathErrorException('Profiling path is invalid.')
  251. if not os.path.isdir(profiling_path):
  252. raise ProfilerDirNotFoundException(profiling_path)
  253. return profiling_path
  254. def _search_file(self, profiling_id, device_id):
  255. """
  256. Search all framework files in raw profiling path.
  257. Args:
  258. profiling_id (str): The profiling ID.
  259. device_id (str): The device ID.
  260. Raises:
  261. ProfilerFileNotFoundException: If the framework files are not found.
  262. """
  263. # first search in the JOB dir, and if not, search in the sub directory
  264. # in the JOB
  265. self._search_file_from_job_path(device_id, search_in_sub_path=False)
  266. if self._backend_type is None:
  267. self._search_file_from_job_path(device_id, search_in_sub_path=True)
  268. self._search_file_from_data_path(profiling_id, device_id)
  269. if self._backend_type is None:
  270. raise ProfilerFileNotFoundException('Framework')
  271. self._framework_path['graph'].sort()
  272. self._framework_path['task'].sort()
  273. def _search_file_from_job_path(self, device_id, search_in_sub_path=False):
  274. """
  275. Search framework files from job path.
  276. Args:
  277. device_id (str): The device ID.
  278. search_in_sub_path (bool): `True` if search file in profiling dir,
  279. else search in profiling sub dir. Default: False.
  280. Raises:
  281. ProfilerRawFileException: If the framework file type is inconsistent.
  282. ProfilerDeviceIdMismatchException: If the device id is mismatch
  283. with framework in the raw dir.
  284. """
  285. profiling_dir = os.path.join(self._profiling_path, 'data') \
  286. if search_in_sub_path else self._profiling_path
  287. if not os.path.isdir(profiling_dir):
  288. return
  289. files = os.listdir(profiling_dir)
  290. for file in files:
  291. pattern = re.search(self._regex_framework, file)
  292. if not pattern or file.endswith('.done'):
  293. continue
  294. attrs = pattern.groupdict()
  295. device_id_in_path = attrs.get('device_id')
  296. if device_id_in_path != device_id:
  297. raise ProfilerDeviceIdMismatchException()
  298. data_type = attrs.get('data_type')
  299. if data_type.startswith('vm.'):
  300. if self._backend_type and self._backend_type != 'vm':
  301. raise ProfilerRawFileException('Backend type is inconsistent.')
  302. self._backend_type = 'vm'
  303. data_type = data_type.split('.')[1]
  304. else:
  305. if self._backend_type and self._backend_type != 'ge':
  306. raise ProfilerRawFileException('Backend type is inconsistent.')
  307. self._backend_type = 'ge'
  308. if data_type.startswith('graph_desc_info'):
  309. self._framework_path['graph'].append(
  310. os.path.join(profiling_dir, file)
  311. )
  312. elif data_type.startswith('task_desc_info'):
  313. self._framework_path['task'].append(
  314. os.path.join(profiling_dir, file)
  315. )
  316. elif data_type.startswith('point'):
  317. self._framework_path['point'].append(
  318. os.path.join(profiling_dir, file)
  319. )
  320. def _search_file_from_data_path(self, profiling_id, device_id):
  321. """
  322. Search framework files from data path.
  323. Args:
  324. profiling_id (str): The profiling ID.
  325. device_id (str): The device ID.
  326. Raises:
  327. ProfilerRawFileException: If the framework file type is inconsistent.
  328. ProfilerDeviceIdMismatchException: If the device id is mismatch
  329. with framework in the raw dir.
  330. """
  331. profiling_data_path = os.path.join(
  332. self._raw_data_dir, 'container', device_id, 'data'
  333. )
  334. if not os.path.isdir(profiling_data_path):
  335. return
  336. files = os.listdir(profiling_data_path)
  337. for file in files:
  338. pattern = re.search(self._regex_framework_in_data, file)
  339. if not pattern or file.endswith('.done') or file.endswith('.zip'):
  340. continue
  341. attrs = pattern.groupdict()
  342. profiling_id_in_path = attrs.get('profiling_id')
  343. if profiling_id_in_path != profiling_id:
  344. continue
  345. device_id_in_path = attrs.get('device_id')
  346. if device_id_in_path != device_id:
  347. raise ProfilerDeviceIdMismatchException()
  348. data_type = attrs.get('data_type')
  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, 'profiler')
  384. except ValidationError:
  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. with open(path, 'r') as file:
  395. for task_info in file:
  396. infos = task_info.strip('\n').split(' ')
  397. # key is op name, values is task id, stream id, block_dim
  398. self._task_cache[infos[0]] = [infos[2], infos[3], infos[1]]
  399. # if the task id is less than the task id threshold, the
  400. # stream id and task id correspond to an operator
  401. task_id = infos[2]
  402. if int(task_id) < self._task_id_threshold:
  403. task_id = '_'.join([infos[3], task_id])
  404. self._task_id_full_op_name_dict[task_id] = infos[0]
  405. def _parse_graph_files_and_save(self, task_cache):
  406. """
  407. Parse the framework graph files and save the framework information.
  408. Args:
  409. task_cache (dict): The task information cache.
  410. """
  411. with open(self._save_path, 'w') as save_file:
  412. csv_writer = csv.writer(save_file)
  413. csv_writer.writerow(self._col_names)
  414. for path in self._framework_path['graph']:
  415. with open(path, 'r') as graph_file:
  416. for graph_info in graph_file:
  417. result = self._parse_one_row_graph_info(graph_info)
  418. task_info = task_cache.get(result[0])
  419. if task_info:
  420. task_info.extend(result)
  421. csv_writer.writerow(task_info)
  422. del task_cache[result[0]]
  423. else:
  424. save_info = [None, None, None]
  425. save_info.extend(result)
  426. csv_writer.writerow(save_info)
  427. none_list = [None, None, None, None]
  428. for key, value in task_cache.items():
  429. value.append(key)
  430. value.extend(none_list)
  431. csv_writer.writerow(value)
  432. def _parse_one_row_graph_info(self, row_info):
  433. """
  434. Parse the graph information in one row.
  435. Args:
  436. row_info (str): One row graph information.
  437. Returns:
  438. list[str], the parsed graph information.
  439. """
  440. full_op_name = None
  441. op_name = None
  442. subgraph_name = None
  443. op_type = None
  444. op_info = dict()
  445. cur_op_info_key = None
  446. infos = row_info.strip('\n').split(' ')
  447. for info in infos:
  448. attr_name, attr_value = info.split(':', 1)
  449. if attr_name == 'op_name':
  450. full_op_name = attr_value
  451. subgraph_name = self._get_subgraph_name(full_op_name)
  452. op_name = self._get_op_name(full_op_name, subgraph_name)
  453. elif attr_name == 'op_type':
  454. op_type = attr_value
  455. elif attr_name in ['input_id', 'output_id']:
  456. cur_op_info_key = '{}_{}'.format(
  457. attr_name.split('_')[0], attr_value
  458. )
  459. op_info[cur_op_info_key] = dict()
  460. elif attr_name in self._graph_attr_name:
  461. op_attr = attr_name.split('_', 1)[1]
  462. if op_attr == 'shape':
  463. attr_value = attr_value.strip('"')
  464. if self._backend_type == 'vm':
  465. if op_attr == 'data_type':
  466. attr_value = VmDataType.get_data_type_name(
  467. int(attr_value)
  468. )
  469. else:
  470. if op_attr == 'data_type':
  471. attr_value = GeDataType.get_data_type_name(
  472. int(attr_value)
  473. )
  474. elif op_attr == 'format':
  475. attr_value = GeFormat.get_format_name(int(attr_value))
  476. op_info[cur_op_info_key][op_attr] = attr_value
  477. # the list info are full_op_name, op_name, op_type, subgraph, op_info
  478. return [full_op_name, op_name, op_type, subgraph_name,
  479. json.dumps(op_info)]
  480. def _get_subgraph_name(self, full_op_name):
  481. """
  482. Get subgraph name.
  483. Args:
  484. full_op_name (str): The full operator name.
  485. Returns:
  486. str, the subgraph name.
  487. """
  488. subgraph_name = full_op_name.split('/', 1)[0]
  489. if subgraph_name in ['Default', 'Gradients']:
  490. return subgraph_name
  491. return None
  492. def _get_op_name(self, full_op_name, subgraph_name):
  493. """
  494. Get operator name.
  495. Args:
  496. full_op_name (str): The full operator name.
  497. subgraph_name (str): The subgraph name.
  498. Returns:
  499. str, the operator name.
  500. """
  501. if subgraph_name is None:
  502. return full_op_name
  503. if self._backend_type == 'vm':
  504. return full_op_name.split('/')[-1]
  505. strs = full_op_name.split(subgraph_name + '/')
  506. op_name = None
  507. for name_str in strs:
  508. if not name_str:
  509. continue
  510. if op_name is None:
  511. op_name = name_str.split('/')[-1]
  512. else:
  513. op_name = '+'.join([op_name, name_str.split('/')[-1]])
  514. return op_name
  515. def _parse_point_files(self):
  516. """Parse the framework point files."""
  517. for path in self._framework_path['point']:
  518. with open(path, 'r') as file:
  519. for point_info in file:
  520. infos = point_info.strip('\n').split(' ')
  521. self._point_info[int(infos[0])] = infos[1]