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 28 kB

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