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.

watchpoint_handler.py 31 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. """Define the watchpoint stream handler."""
  16. from mindinsight.debugger.conditionmgr.condition import ValueTypeEnum
  17. from mindinsight.debugger.conditionmgr.condition import ParamTypeEnum
  18. from mindinsight.debugger.common.exceptions.exceptions import DebuggerParamValueError, \
  19. DebuggerParamTypeError
  20. from mindinsight.debugger.common.log import LOGGER as log
  21. from mindinsight.debugger.common.utils import is_scope_type
  22. from mindinsight.debugger.proto.debug_grpc_pb2 import SetCMD
  23. from mindinsight.debugger.stream_cache.watchpoint import Watchpoint, WatchpointHit, \
  24. WatchNodeTree
  25. from mindinsight.debugger.stream_handler.base_handler import StreamHandlerBase
  26. RANGE_START = 'range_start_inclusive'
  27. RANGE_END = 'range_end_inclusive'
  28. class WatchpointHandler(StreamHandlerBase):
  29. """Watchpoint Handler."""
  30. def __init__(self):
  31. self._watchpoints = {}
  32. # list of ids of new created watchpoints
  33. self._created_watchpoints = []
  34. # list of SetCMD of watchpoints to be deleted
  35. self._deleted_watchpoints = []
  36. # dict of <id, Watchpoint> of watchpoints to be updated
  37. self._updated_watchpoints = {}
  38. # the collection of watched node full names, which have been sent to MindSpore
  39. self._latest_id = 0
  40. self._cache_set_cmd = {}
  41. # whether the watchpoint list has been changed since last step
  42. self._outdated = False
  43. def put(self, value):
  44. """
  45. Put Watchpoint into watchpoint handler.
  46. Args:
  47. value (Watchpoint): The name of nodes that have been chosen.
  48. """
  49. new_id = value.watchpoint_id
  50. self._watchpoints[new_id] = value
  51. self._created_watchpoints.append(new_id)
  52. self._updated_watchpoints[new_id] = value
  53. self._latest_id = new_id
  54. log.debug("Put watchpoint %d into cache.", new_id)
  55. def sync_set_cmd(self, set_cmds):
  56. """Clean temp watchpoints."""
  57. self._outdated = False
  58. self._created_watchpoints = []
  59. self._deleted_watchpoints = []
  60. self._updated_watchpoints = {}
  61. for set_cmd in set_cmds:
  62. self._cache_set_cmd[set_cmd.id] = set_cmd
  63. def clean_cache_set_cmd(self, set_cmd):
  64. """Clean cache set command."""
  65. self._cache_set_cmd.pop(set_cmd.id, None)
  66. def get_watchpoint_by_id(self, watchpoint_id):
  67. """Get watchpoint by watchpoint id."""
  68. res = self.get(watchpoint_id)
  69. watchpoint = res.get('watch_points')[0]
  70. return watchpoint
  71. def get(self, filter_condition=None):
  72. """
  73. Get the watchpoints.
  74. Args:
  75. filter_condition (Union[None, int]): The filter conditions. Get watchpoint by
  76. id. If None, return all watchpoint. Default: None.
  77. Returns:
  78. dict, the watchpoint list.
  79. """
  80. reply = []
  81. if not filter_condition:
  82. # get watch condition list
  83. for _, watchpoint in self._watchpoints.items():
  84. watchpoint_info = watchpoint.get_watch_condition_info()
  85. reply.append(watchpoint_info)
  86. else:
  87. self.validate_watchpoint_id(filter_condition)
  88. reply = [self._watchpoints.get(filter_condition)]
  89. log.debug("get the watch points with filter_condition:%s", filter_condition)
  90. return {'watch_points': reply}
  91. def get_pending_commands(self, multi_card_graph_stream):
  92. """
  93. Get all watchpoint in SetCMD proto format.
  94. Args:
  95. multi_card_graph_stream (MultiCardGraphHandler): Multi card graph handler.
  96. Returns:
  97. list[SetCMD], updated watchpoint to be sent to MindSpore.
  98. """
  99. newly_set_cmds = []
  100. for _, watchpoint in self._updated_watchpoints.items():
  101. # construct set command with leaf nodes
  102. watch_nodes_for_devices = watchpoint.get_watch_nodes()
  103. leaf_watch_nodes_for_devices = {}
  104. for rank_id, watch_nodes in watch_nodes_for_devices.items():
  105. graph_stream = multi_card_graph_stream.get_graph_handler_by_rank_id(rank_id)
  106. leaf_watch_nodes = self._expand_to_leaf_nodes(graph_stream, watch_nodes)
  107. leaf_watch_nodes_for_devices[rank_id] = leaf_watch_nodes
  108. newly_set_cmds.append(watchpoint.get_pending_cmd(leaf_watch_nodes_for_devices))
  109. newly_set_cmds.extend(self._deleted_watchpoints)
  110. self.sync_set_cmd(newly_set_cmds)
  111. return list(self._cache_set_cmd.values())
  112. @staticmethod
  113. def _expand_to_leaf_nodes(graph_stream, watch_nodes):
  114. """
  115. Get all leaf node basic info according to watch nodes.
  116. Args:
  117. graph_stream (GraphHandler): Graph handler.
  118. watch_nodes (list[NodeBasicInfo]): The list of watch node basic infos.
  119. Returns:
  120. list[NodeBasicInfo], expanded leaf basic node infos.
  121. """
  122. leaf_watch_nodes = []
  123. for node in watch_nodes:
  124. if is_scope_type(node.type):
  125. pure_node_name = ''
  126. if len(node.name.split('/')) > 1:
  127. graph_name, pure_node_name = node.name.split('/', 1)
  128. else:
  129. graph_name = node.name
  130. search_node_infos = graph_stream.get_node_basic_info_by_scope(pure_node_name, graph_name=graph_name)
  131. leaf_watch_nodes.extend(search_node_infos)
  132. else:
  133. leaf_watch_nodes.append(node)
  134. return leaf_watch_nodes
  135. def is_recheckable(self):
  136. """
  137. Check if current status is able to recheck.
  138. Returns:
  139. bool, if enable to recheck.
  140. """
  141. return self._outdated
  142. def set_watch_nodes(self, graph, graph_stream, watch_point_id, graph_name=None, rank_id=0):
  143. """
  144. set watch nodes for graph.
  145. Args:
  146. graph (dict): The graph with list of nodes.
  147. graph_stream (GraphHandler): The graph handler.
  148. watch_point_id (int): The id of watchpoint.
  149. graph_name (str): The graph name.
  150. rank_id (int): The rank id.
  151. """
  152. if not (watch_point_id and graph):
  153. return
  154. log.debug("add watch flags")
  155. watchpoint = self._watchpoints.get(watch_point_id)
  156. self._set_watch_status_recursively(graph, graph_stream, watchpoint, graph_name, rank_id)
  157. def _set_watch_status_recursively(self, graph, graph_stream, watchpoint, graph_name=None, rank_id=0):
  158. """Set watch status to graph."""
  159. if graph.get('children'):
  160. self._set_watch_status_recursively(
  161. graph.get('children'), graph_stream, watchpoint, graph_name, rank_id=0)
  162. if graph.get('nodes'):
  163. _ = self._set_watch_state_for_nodes(graph['nodes'], graph_stream, watchpoint, graph_name, rank_id)
  164. def _set_watch_state_for_nodes(self, nodes, graph_stream, watchpoint, graph_name, rank_id=0):
  165. """
  166. Set watch state for nodes.
  167. Args:
  168. nodes (list[Node]): List of node info.
  169. Returns:
  170. int, the number of all watched nodes.
  171. """
  172. all_watched_num = 0
  173. valid_node_num = len(nodes)
  174. # initialize the state of current node.
  175. state = WatchNodeTree.NOT_WATCH
  176. for node in nodes:
  177. node_name = node.get('name')
  178. # search result could have `nodes` in nodes object
  179. if node.get('nodes'):
  180. flag = self._set_watch_state_for_nodes(node.get('nodes'), graph_stream, watchpoint, graph_name, rank_id)
  181. else:
  182. full_name = graph_stream.get_full_name(node_name, graph_name)
  183. new_node_name = node_name if graph_name is None else '/'.join([graph_name, node_name])
  184. flag = watchpoint.get_node_status(new_node_name, node.get('type'), full_name, rank_id)
  185. node['watched'] = flag
  186. if flag == WatchNodeTree.NOT_WATCH:
  187. continue
  188. state = WatchNodeTree.PARTIAL_WATCH
  189. if flag == WatchNodeTree.INVALID:
  190. valid_node_num -= 1
  191. elif flag == WatchNodeTree.TOTAL_WATCH:
  192. all_watched_num += 1
  193. # update the watch status of current node
  194. if not valid_node_num:
  195. state = WatchNodeTree.INVALID
  196. elif all_watched_num == valid_node_num:
  197. state = WatchNodeTree.TOTAL_WATCH
  198. return state
  199. def create_watchpoint(self, condition_mgr, watch_condition, watch_nodes=None, watch_point_id=None, name=None,
  200. device_amount=8):
  201. """
  202. Create watchpoint.
  203. Args:
  204. condition_mgr (ConditionMgr): Instance of ConditionMgr.
  205. watch_condition (dict): The watch condition.
  206. "condition": {
  207. id: "tensor_too_large",
  208. "params": [
  209. {
  210. "name": "abs_mean_gt",
  211. "value": 1.1
  212. }
  213. ]
  214. }
  215. - id (str): Id of condition.
  216. - param (list[dict]): The list of param for this condition.
  217. watch_nodes (dict[list[NodeBasicInfo]]): The list of node basic info.
  218. watch_point_id (int): The id of watchpoint.
  219. name (str): The name of watchpoint.
  220. device_amount (int): The amount of devices.
  221. Returns:
  222. int, the new id of watchpoint.
  223. """
  224. validate_watch_condition(condition_mgr, watch_condition)
  225. watch_condition = set_default_param(condition_mgr, watch_condition)
  226. new_id = self._latest_id + 1
  227. watchpoint = Watchpoint(new_id, watch_condition, name)
  228. if watch_nodes:
  229. for rank_id, watch_nodes_for_device in watch_nodes.items():
  230. validate_rank_id(rank_id, device_amount)
  231. watchpoint.add_nodes(watch_nodes_for_device, rank_id)
  232. elif watch_point_id:
  233. self.validate_watchpoint_id(watch_point_id)
  234. watchpoint.copy_nodes_from(self._watchpoints.get(watch_point_id))
  235. self.put(watchpoint)
  236. self._outdated = True
  237. return new_id
  238. def update_watchpoint(self, watch_point_id, watch_nodes, watched=False, rank_id=0):
  239. """
  240. Update watchpoint.
  241. Args:
  242. watch_point_id (int): The id of watchpoint.
  243. watch_nodes (list[NodeBasicInfo]): The list of node basic info.
  244. watched (bool): The update operator on nodes. If False, remove nodes from watch nodes.
  245. If True, add nodes to watch nodes. Default: False.
  246. rank_id (int): The rank id.
  247. """
  248. self.validate_watchpoint_id(watch_point_id)
  249. watchpoint = self._watchpoints.get(watch_point_id)
  250. if watched:
  251. watchpoint.add_nodes(watch_nodes, rank_id)
  252. else:
  253. watchpoint.remove_nodes(watch_nodes, rank_id)
  254. self._updated_watchpoints[watch_point_id] = watchpoint
  255. self._outdated = True
  256. log.debug("Update watchpoint %d in cache.", watch_point_id)
  257. def delete_watchpoint(self, watch_point_id=None):
  258. """
  259. Delete watchpoint.
  260. Args:
  261. watch_point_id (Union[None, int]): The id of watchpoint.
  262. If None, delete all watchpoints. Default: None.
  263. """
  264. if watch_point_id is None:
  265. watch_point_ids = [sub_id for sub_id, _ in self._watchpoints.items()]
  266. else:
  267. self.validate_watchpoint_id(watch_point_id)
  268. watch_point_ids = [watch_point_id]
  269. for single_id in watch_point_ids:
  270. self._delete_single_watchpoint(single_id)
  271. self._outdated = True
  272. def _delete_single_watchpoint(self, watch_point_id):
  273. """
  274. Delete single watchpoint.
  275. Args:
  276. watch_point_id (int): The id of watchpoint.
  277. """
  278. self._watchpoints.pop(watch_point_id)
  279. # if the watchpoint has not been created by MindSpore, clean the relative cache directly
  280. if watch_point_id in self._created_watchpoints:
  281. self._created_watchpoints.remove(watch_point_id)
  282. self._updated_watchpoints.pop(watch_point_id)
  283. log.debug("Cancel create watchpoint %d in cache.", watch_point_id)
  284. return
  285. set_cmd = SetCMD()
  286. set_cmd.id = watch_point_id
  287. set_cmd.delete = True
  288. self._deleted_watchpoints.append(set_cmd)
  289. log.debug("Delete watchpoint %d in cache.", watch_point_id)
  290. def validate_watchpoint_id(self, watch_point_id):
  291. """Validate watchpoint id."""
  292. if not isinstance(watch_point_id, int):
  293. log.error("Invalid watchpoint id %s. The watch point id should be int.", watch_point_id)
  294. raise DebuggerParamTypeError("Watchpoint id should be int type.")
  295. if watch_point_id and watch_point_id not in self._watchpoints:
  296. log.error("Invalid watchpoint id: %d.", watch_point_id)
  297. raise DebuggerParamValueError("Invalid watchpoint id: {}".format(watch_point_id))
  298. class MultiCardWatchpointHitHandler:
  299. """Multi-card Watchpoint-hit Handler."""
  300. def __init__(self):
  301. self.watchpoint_hit_handlers = {0: WatchpointHitHandler()}
  302. def get_hit_handler_by_rank_id(self, rank_id=0):
  303. """Get handler by rank id."""
  304. if rank_id in self.watchpoint_hit_handlers:
  305. return self.watchpoint_hit_handlers.get(rank_id)
  306. log.error("There is no rank id %d.", rank_id)
  307. raise ValueError
  308. def put(self, value):
  309. """Put watchpoint hit into cache."""
  310. for rank_id, tensor_hit_values in value.items():
  311. if rank_id not in self.watchpoint_hit_handlers:
  312. self.watchpoint_hit_handlers[rank_id] = WatchpointHitHandler()
  313. cur_hit_handler = self.watchpoint_hit_handlers[rank_id]
  314. for tensor_hit_value in tensor_hit_values:
  315. cur_hit_handler.put(tensor_hit_value)
  316. def get(self, filter_condition=None, rank_id=0):
  317. """Get the graph of specific node for specific device."""
  318. if rank_id in self.watchpoint_hit_handlers:
  319. return self.watchpoint_hit_handlers.get(rank_id).get(filter_condition)
  320. log.error("There is no rank id %d.", rank_id)
  321. raise ValueError
  322. def update_tensor_history(self, tensor_history, rank_id):
  323. """
  324. Add hit flag to tensor history.
  325. Args:
  326. tensor_history (dict): The tensor history.
  327. rank_id (int): The rank id.
  328. """
  329. if rank_id in self.watchpoint_hit_handlers:
  330. self.watchpoint_hit_handlers[rank_id].update_tensor_history(tensor_history)
  331. else:
  332. for tensor_info in tensor_history.get('tensor_history'):
  333. tensor_info['is_hit'] = False
  334. def check_rank_id(self, rank_id):
  335. """check if has the rank id."""
  336. return rank_id in self.watchpoint_hit_handlers
  337. def clean(self):
  338. """Clean cache."""
  339. self.__init__()
  340. class WatchpointHitHandler(StreamHandlerBase):
  341. """Watchpoint hit handler."""
  342. def __init__(self):
  343. # dict of <ui node_name, dict of <slot, WatchpointHit>>,
  344. self._ordered_hits = []
  345. self._multi_graph_hits = {}
  346. @property
  347. def empty(self):
  348. """Whether the watchpoint hit is empty."""
  349. return not self._multi_graph_hits
  350. def put(self, value):
  351. """
  352. Put value into watchpoint hit cache. Called by grpc server.
  353. Args:
  354. value (dict): The watchpoint hit info.
  355. - tensor_proto (TensorProto): The message about hit tensor.
  356. - watchpoint (Watchpoint): The Watchpoint that a node hit.
  357. - node_name (str): The UI node name.
  358. - graph_name (str): The graph name.
  359. - error_code (int): The code of errors.
  360. """
  361. watchpoint_hit = WatchpointHit(
  362. tensor_proto=value.get('tensor_proto'),
  363. watchpoint=value.get('watchpoint'),
  364. node_name=value.get('node_name'),
  365. graph_name=value.get('graph_name')
  366. )
  367. if 'error_code' in value.keys():
  368. watchpoint_hit.error_code = value.get('error_code')
  369. # get all hit watchpoints according to node name ans tensor slot
  370. watchpoint_hits = self._get_watchpoints_by_tensor_name(watchpoint_hit.graph_name, watchpoint_hit.node_name,
  371. watchpoint_hit.slot)
  372. if watchpoint_hit not in watchpoint_hits:
  373. watchpoint_hits.append(watchpoint_hit)
  374. def _get_watchpoints_by_tensor_name(self, graph_name, node_name, slot):
  375. """
  376. Get hit tensors according to ui node name and slot.
  377. Args:
  378. node_name (str): The node name.
  379. slot (str): The tensor slot.
  380. Returns:
  381. list, list of watchpoints.
  382. """
  383. index = self._multi_graph_hits.get((graph_name, node_name))
  384. if index is None:
  385. hit_node = {}
  386. self._ordered_hits.append(hit_node)
  387. index = len(self._ordered_hits) - 1
  388. self._multi_graph_hits[(graph_name, node_name)] = index
  389. hit_node = self._ordered_hits[index]
  390. hit_tensors = hit_node.get(slot)
  391. if hit_tensors is None:
  392. hit_tensors = []
  393. hit_node[slot] = hit_tensors
  394. return hit_tensors
  395. def get(self, filter_condition=None):
  396. """
  397. Get watchpoint hit list.
  398. Args:
  399. filter_condition (str): Get the watchpoint hit according to specified node name.
  400. If not given, get all watchpoint hits. Default: None.
  401. Returns:
  402. dict, the watchpoint hit list.
  403. """
  404. reply = None
  405. if filter_condition is None:
  406. log.debug("Get all watchpoint hit list.")
  407. reply = self.get_watchpoint_hits()
  408. else:
  409. log.debug("Get the watchpoint for node: <%s>.", filter_condition)
  410. index = self._multi_graph_hits.get(("", filter_condition))
  411. if index is not None:
  412. reply = self._ordered_hits[index]
  413. return reply
  414. def group_by(self, group_condition):
  415. """
  416. Return the watchpoint hits by group condition.
  417. Args:
  418. group_condition (dict): The group conditions.
  419. - limit (int): The limit number of watchpoint hits each page.
  420. - offset (int): The page offset.
  421. - node_name (str): The node name.
  422. - graph_name (str): The graph name.
  423. Returns:
  424. dict, the watchpoint hit list.
  425. """
  426. node_name = group_condition.get('node_name')
  427. # get all watchpoint hit list
  428. if node_name is None:
  429. reply = self._get_by_offset(group_condition)
  430. else:
  431. reply = self._get_by_name(group_condition)
  432. return reply
  433. def _get_by_offset(self, group_condition):
  434. """Return the list of watchpoint hits on the offset page."""
  435. limit = group_condition.get('limit')
  436. offset = group_condition.get('offset')
  437. if not isinstance(limit, int) or not isinstance(offset, int):
  438. log.error("Param limit or offset is not a integer")
  439. raise DebuggerParamValueError("Param limit or offset is not a integer")
  440. watch_point_hits = []
  441. total = len(self._ordered_hits)
  442. if limit * offset >= total and offset != 0:
  443. log.error("Param offset out of bounds")
  444. raise DebuggerParamValueError("Param offset out of bounds")
  445. if total == 0:
  446. return {}
  447. for watchpoint_hits in self._ordered_hits[(limit * offset): (limit * (offset + 1))]:
  448. self._get_tensors(watchpoint_hits, watch_point_hits)
  449. return {
  450. 'watch_point_hits': watch_point_hits,
  451. 'offset': offset,
  452. 'total': total
  453. }
  454. def _get_by_name(self, group_condition):
  455. """Return the list of watchpoint hits by the group condition."""
  456. limit = group_condition.get('limit')
  457. if not isinstance(limit, int) or limit == 0:
  458. log.error("Param limit is 0 or not a integer")
  459. raise DebuggerParamValueError("Param limit is 0 or not a integer")
  460. index = self._multi_graph_hits.get((group_condition.get('graph_name'), group_condition.get('node_name')))
  461. if index is not None:
  462. group_condition['offset'] = index//limit
  463. return self._get_by_offset(group_condition)
  464. return {}
  465. def get_watchpoint_hits(self):
  466. """Return the list of watchpoint hits."""
  467. watch_point_hits = []
  468. for watchpoint_hits in self._ordered_hits:
  469. self._get_tensors(watchpoint_hits, watch_point_hits)
  470. return {'watch_point_hits': watch_point_hits}
  471. def _get_tensors(self, watchpoint_hits, watch_point_hits):
  472. """Get the tensors info for the watchpoint_hits."""
  473. tensors = []
  474. graph_name = None
  475. node_name = None
  476. for slot, tensor_hits in watchpoint_hits.items():
  477. if graph_name is None:
  478. graph_name = tensor_hits[0].graph_name
  479. if node_name is None:
  480. node_name = tensor_hits[0].node_name
  481. tensor_info = self._get_tensor_hit_info(slot, tensor_hits)
  482. tensors.append(tensor_info)
  483. watch_point_hits.append({
  484. 'node_name': node_name,
  485. 'tensors': tensors,
  486. 'graph_name': graph_name
  487. })
  488. @staticmethod
  489. def _get_tensor_hit_info(slot, tensor_hits):
  490. """
  491. Get watchpoint hit info of specified tensor.
  492. Args:
  493. slot (str): Slot id.
  494. tensor_hits (list): A list of watchpoint hit objects that the tensor hit.
  495. Returns:
  496. dict, tensor hit info.
  497. """
  498. res = {}
  499. watch_points = []
  500. for tensor_hit in tensor_hits:
  501. error_code = tensor_hit.error_code
  502. error_list = _get_error_list(error_code)
  503. watchpoint = tensor_hit.watchpoint
  504. watchpoint['error_code'] = error_code
  505. watchpoint['error_list'] = error_list
  506. watch_points.append(watchpoint)
  507. if watch_points:
  508. watch_points.sort(key=lambda watch_point: watch_point.get('id'))
  509. res = {
  510. 'slot': slot,
  511. 'watch_points': watch_points
  512. }
  513. return res
  514. def _is_tensor_hit(self, tensor_name, graph_name):
  515. """
  516. Check if the tensor is record in hit cache.
  517. Args:
  518. tensor_name (str): The name of ui tensor name.
  519. graph_name (str): The name of ui graph name
  520. Returns:
  521. bool, if the tensor is hit.
  522. """
  523. node_name, slot = tensor_name.rsplit(':', 1)
  524. index = self._multi_graph_hits.get((graph_name, node_name))
  525. if index is not None:
  526. watchpoint_hits = self._ordered_hits[index].get(slot)
  527. return bool(watchpoint_hits)
  528. return False
  529. def update_tensor_history(self, tensor_history):
  530. """
  531. Add hit flag to tensor history.
  532. Args:
  533. tensor_history (dict): The tensor history.
  534. """
  535. if not self._multi_graph_hits:
  536. return
  537. # add hit tensor names to `tensor_names`
  538. for tensor_info in tensor_history.get('tensor_history'):
  539. tensor_name = tensor_info['name']
  540. graph_name = tensor_info['graph_name']
  541. hit_flag = self._is_tensor_hit(tensor_name, graph_name)
  542. tensor_info['is_hit'] = hit_flag
  543. def get_tensor_hit_infos(self, tensor_name, graph_name):
  544. """
  545. Get all hit information of a tensor.
  546. Args:
  547. tensor_name (str): Tensor name showed on UI.
  548. Returns:
  549. dict, tensor hit info.
  550. """
  551. tensor_hit_info = {}
  552. if self._is_tensor_hit(tensor_name, graph_name):
  553. node_name, slot = tensor_name.rsplit(':', 1)
  554. tensor_hits = self._get_watchpoints_by_tensor_name(graph_name, node_name, slot)
  555. tensor_hit_info = self._get_tensor_hit_info(slot, tensor_hits)
  556. return tensor_hit_info
  557. def validate_watch_condition(condition_mgr, watch_condition):
  558. """Validate watch condition."""
  559. if not isinstance(watch_condition, dict):
  560. log.error("<watch_condition> should be dict. %s received.", watch_condition)
  561. raise DebuggerParamTypeError("<watch_condition> should be dict.")
  562. # validate condition_id
  563. condition_id = watch_condition.get('id')
  564. if condition_id not in condition_mgr.conditions.keys():
  565. log.error("Invalid watch condition. Acceptable values are <%s>. %s received.",
  566. str(condition_mgr.conditions.keys()), condition_id)
  567. raise DebuggerParamValueError("Invalid watch condition value.")
  568. # validate param
  569. validate_watch_condition_params(condition_mgr, watch_condition)
  570. def validate_watch_condition_params(condition_mgr, watch_condition):
  571. """
  572. Validate watch condition parameters.
  573. Args:
  574. condition_mgr (ConditionMgr): Instance of ConditionMgr.
  575. watch_condition (dict): Watch condition.
  576. - id (str): Condition id. Should be in WATCHPOINT_CONDITION_MAPPING.
  577. - param (list): Condition value. Should be given for comparison condition. The value
  578. will be translated to np.float32.
  579. """
  580. condition_id = watch_condition.get('id')
  581. params = watch_condition.get('params')
  582. condition = condition_mgr.get_condition(condition_id)
  583. if condition_id in condition_mgr.get_no_param_condition():
  584. if params:
  585. log.error("No param is expected for %s condition", condition_id)
  586. raise DebuggerParamValueError("No param is expected.")
  587. return
  588. check_param_num = 0
  589. support_params = set()
  590. defined_support_params = set()
  591. range_param = {RANGE_START: None, RANGE_END: None}
  592. for param in params:
  593. if len(param) > 2:
  594. log.error("Invalid param keys for condition: %s", condition_id)
  595. raise DebuggerParamValueError("Invalid param keys.")
  596. condition_param_name = param.get("name")
  597. if condition_param_name not in condition.names:
  598. log.error("Invalid name of parameter for condition: %s, available values: %s",
  599. condition_id, condition.names)
  600. raise DebuggerParamValueError("Invalid name of parameter.")
  601. condition_param = condition.get_parameter_definition(condition_param_name)
  602. validate_param_type(condition_id, condition_param, param)
  603. if not condition_param.is_valid(param.get("value")):
  604. log.error("Param %s out of range for condition: %s", condition_param_name, condition_id)
  605. raise DebuggerParamValueError("Parameter out of range.")
  606. if condition_param.param_type == ParamTypeEnum.CHECK_PARAM.value:
  607. if condition_param.required_params:
  608. defined_support_params = set(condition_param.required_params)
  609. check_param_num += 1
  610. else:
  611. support_params.add(condition_param.name)
  612. if condition_param_name in range_param:
  613. range_param[condition_param_name] = param.get("value")
  614. if check_param_num > 1:
  615. log.error("Multiple check params for condition: %s", condition_id)
  616. raise DebuggerParamValueError("Multiple check params.")
  617. if support_params != defined_support_params:
  618. log.error("Invalid support params for condition: %s", condition_id)
  619. raise DebuggerParamValueError("Invalid support params.")
  620. if range_param.get(RANGE_START) is not None and \
  621. range_param.get(RANGE_END) is not None and range_param.get(RANGE_START) > \
  622. range_param.get(RANGE_END):
  623. log.error("Invalid support params for condition: %s", condition_id)
  624. raise DebuggerParamValueError("Invalid support params.")
  625. def validate_param_type(condition_id, condition_param, param):
  626. """
  627. Validate parameter type.
  628. Args:
  629. condition_id (str): Condition id. Should be in WATCHPOINT_CONDITION_MAPPING.
  630. condition_param (ConditionParameter): Condition Parameter object.
  631. param (dict): Condition parameter value.
  632. """
  633. if condition_param.type.name in (ValueTypeEnum.FLOAT64.name, ValueTypeEnum.INT64.name) \
  634. and not isinstance(param.get("value"), (float, int)):
  635. log.error("Number param should be given for condition: %s", condition_id)
  636. raise DebuggerParamValueError("Number param should be given.")
  637. if condition_param.type.name == ValueTypeEnum.BOOL.name \
  638. and not isinstance(param.get("value"), bool):
  639. log.error("Bool param should be given for condition: %s", condition_id)
  640. raise DebuggerParamValueError("Bool param should be given.")
  641. def set_default_param(condition_mgr, watch_condition):
  642. """
  643. Set default param.
  644. Args:
  645. condition_mgr (ConditionMgr): Instance of ConditionMgr.
  646. watch_condition (dict): The watch condition.
  647. "condition": {
  648. id: "tensor_too_large",
  649. "params": [
  650. {
  651. "name": "abs_mean_gt",
  652. "value": 1.1
  653. }
  654. ]
  655. }
  656. - id (str): Id of condition.
  657. - param (list[dict]): The list of param for this condition.
  658. Returns:
  659. dict, the new watch_condition.
  660. """
  661. condition_id = watch_condition.get('id')
  662. condition = condition_mgr.get_condition(condition_id)
  663. for param in condition.parameters:
  664. if not param.visible_on_ui and not param.support_disable:
  665. watch_condition["params"].append({
  666. "name": param.name,
  667. "value": param.default_value
  668. })
  669. watch_condition["abbr"] = condition.abbr
  670. return watch_condition
  671. def _get_error_list(error_code):
  672. """
  673. Get error list.
  674. Args:
  675. error_code (int): The code of errors.
  676. Returns:
  677. list, the error list.
  678. """
  679. all_error_list = ["nan", "inf", "no_prev_tensor"]
  680. error_list = []
  681. for i, error_str in enumerate(all_error_list):
  682. error = (error_code >> i) & 1
  683. if error == 1:
  684. error_list.append(error_str)
  685. return error_list
  686. def validate_rank_id(rank_id, device_amount):
  687. """validate rank id"""
  688. if rank_id >= device_amount:
  689. log.debug("The rank id %d over device amount.", rank_id)