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.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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."""
  16. import copy
  17. from mindinsight.debugger.common.exceptions.exceptions import DebuggerParamValueError
  18. from mindinsight.debugger.common.log import LOGGER as log
  19. from mindinsight.debugger.common.utils import is_scope_type, is_cst_type
  20. from mindinsight.debugger.conditionmgr.conditionmgr import ConditionMgr
  21. from mindinsight.debugger.conditionmgr.common.utils import NodeBasicInfo
  22. from mindinsight.debugger.conditionmgr.condition import ConditionIdEnum
  23. from mindinsight.debugger.proto.debug_grpc_pb2 import SetCMD, WatchCondition
  24. WATCHPOINT_CONDITION_MAPPING = {
  25. ConditionIdEnum.ACTIVATION_RANGE.value: WatchCondition.Condition.tensor_range,
  26. ConditionIdEnum.GRADIENT_EXPLODING.value: WatchCondition.Condition.tensor_general_overflow,
  27. ConditionIdEnum.GRADIENT_TOO_LARGE.value: WatchCondition.Condition.tensor_too_large,
  28. ConditionIdEnum.GRADIENT_VANISHING.value: WatchCondition.Condition.tensor_too_small,
  29. ConditionIdEnum.OPERATOR_OVERFLOW.value: WatchCondition.Condition.overflow,
  30. ConditionIdEnum.TENSOR_ALL_ZERO.value: WatchCondition.Condition.tensor_all_zero,
  31. ConditionIdEnum.TENSOR_OVERFLOW.value: WatchCondition.Condition.tensor_general_overflow,
  32. ConditionIdEnum.TENSOR_RANGE.value: WatchCondition.Condition.tensor_range,
  33. ConditionIdEnum.TENSOR_TOO_LARGE.value: WatchCondition.Condition.tensor_too_large,
  34. ConditionIdEnum.TENSOR_TOO_SMALL.value: WatchCondition.Condition.tensor_too_small,
  35. ConditionIdEnum.WEIGHT_CHANGE_TOO_LARGE.value: WatchCondition.Condition.tensor_change_too_large,
  36. ConditionIdEnum.WEIGHT_CHANGE_TOO_SMALL.value: WatchCondition.Condition.tensor_change_too_small,
  37. ConditionIdEnum.WEIGHT_INITIALIZATION.value: WatchCondition.Condition.tensor_initialization,
  38. ConditionIdEnum.WEIGHT_NOT_CHANGED.value: WatchCondition.Condition.tensor_not_changed,
  39. ConditionIdEnum.WEIGHT_OVERFLOW.value: WatchCondition.Condition.tensor_general_overflow,
  40. ConditionIdEnum.WEIGHT_TOO_LARGE.value: WatchCondition.Condition.tensor_too_large,
  41. ConditionIdEnum.WEIGHT_TOO_SMALL.value: WatchCondition.Condition.tensor_too_small
  42. }
  43. class WatchNodeTree:
  44. """The WatchNode Node Structure."""
  45. INVALID = -1 # the scope node and the nodes below are invalid
  46. NOT_WATCH = 0 # the scope node and the nodes below are not watched
  47. PARTIAL_WATCH = 1 # at least one node under the scope node is not watched
  48. TOTAL_WATCH = 2 # the scope node and the nodes below are all watched
  49. def __init__(self, node_name='', node_type=None, full_name='', watch_status=1):
  50. self._node_name = node_name
  51. self._full_name = full_name
  52. self._node_type = self._translate_node_type(node_type)
  53. self._watch_status = watch_status
  54. self._children = {}
  55. @property
  56. def node_name(self):
  57. """The property of node name."""
  58. return self._node_name
  59. @property
  60. def full_name(self):
  61. """The property of node name."""
  62. return self._full_name
  63. @property
  64. def node_type(self):
  65. """The property of node type."""
  66. return self._node_type
  67. @node_type.setter
  68. def node_type(self, value):
  69. """Set the node type."""
  70. self._node_type = self._translate_node_type(value)
  71. @property
  72. def watch_status(self):
  73. """The property of watch status about current node."""
  74. return self._watch_status
  75. @watch_status.setter
  76. def watch_status(self, value):
  77. """Set the node watch_status."""
  78. self._watch_status = value
  79. def update_metadata(self, node_type, full_name, watch_status):
  80. """Update the metadata for watched node."""
  81. self._full_name = full_name
  82. self._node_type = self._translate_node_type(node_type)
  83. self._watch_status = watch_status
  84. @staticmethod
  85. def _translate_node_type(node_type):
  86. """Translate node type to watch node type."""
  87. flag = node_type
  88. if not node_type or is_scope_type(node_type):
  89. flag = 'scope'
  90. return flag
  91. def get(self, sub_name):
  92. """Get sub node."""
  93. return self._children.get(sub_name)
  94. def get_children(self):
  95. """Get all children."""
  96. for name_scope, sub_watch_node in self._children.items():
  97. yield name_scope, sub_watch_node
  98. def get_children_count(self):
  99. """Get the count of children nodes."""
  100. return len(self._children)
  101. def add_node(self, node_name, node_type, full_name=''):
  102. """
  103. Add watch node to watch node tree.
  104. Args:
  105. node_name (str): The node name.
  106. node_type (str): The node type.
  107. full_name (str): The full name of node.
  108. """
  109. log.debug("Add node %s with type: %s, full_name: %s", node_name, node_type, full_name)
  110. scope_names = node_name.split('/', 1)
  111. if len(scope_names) == 1:
  112. target_node = self.get(node_name)
  113. if not target_node:
  114. self.add(node_name, node_type, full_name, watch_status=WatchNodeTree.TOTAL_WATCH)
  115. else:
  116. target_node.update_metadata(node_type, full_name, WatchNodeTree.TOTAL_WATCH)
  117. return
  118. scope_name, sub_names = scope_names
  119. sub_tree = self.get(scope_name)
  120. if not sub_tree:
  121. sub_tree = self.add(scope_name, watch_status=1)
  122. sub_tree.add_node(sub_names, node_type, full_name)
  123. def add(self, name, node_type=None, full_name='', watch_status=1):
  124. """Add sub WatchPointTree."""
  125. sub_name = '/'.join([self._node_name, name]) if self._node_name else name
  126. sub_tree = WatchNodeTree(sub_name, node_type, full_name, watch_status)
  127. self._children[name] = sub_tree
  128. return sub_tree
  129. def remove_node(self, node_name):
  130. """Remove sub node from current tree."""
  131. log.debug("Remove %s", node_name)
  132. scope_names = node_name.split('/', 1)
  133. sub_tree_name = scope_names[0]
  134. sub_tree = self._children.get(sub_tree_name)
  135. if not sub_tree:
  136. log.error("Failed to find node %s in WatchNodeTree.", sub_tree_name)
  137. raise DebuggerParamValueError("Failed to find node {}".format(sub_tree_name))
  138. if len(scope_names) > 1:
  139. sub_tree.remove_node(scope_names[1])
  140. if sub_tree.watch_status == WatchNodeTree.NOT_WATCH or len(scope_names) == 1:
  141. self._children.pop(sub_tree_name)
  142. self._watch_status = WatchNodeTree.PARTIAL_WATCH if self._children else \
  143. WatchNodeTree.NOT_WATCH
  144. class Watchpoint:
  145. """
  146. The class of watchpoint stream.
  147. Args:
  148. watchpoint_id (int): The id of Watchpoint.
  149. watch_condition (dict): The condition of Watchpoint.
  150. - condition (str): Accept `INF` or `NAN`.
  151. - param (list[float]): Not defined yet.
  152. """
  153. def __init__(self, watchpoint_id, watch_condition, name=None):
  154. self._id = watchpoint_id
  155. self._condition = watch_condition
  156. self._watch_node = WatchNodeTree()
  157. self.name = name
  158. @property
  159. def watchpoint_id(self):
  160. """The property of watchpoint id."""
  161. return self._id
  162. @property
  163. def nodes(self):
  164. """The property of watch nodes."""
  165. return self._watch_node
  166. @property
  167. def condition(self):
  168. """The property of watch condition."""
  169. return self._condition
  170. def copy_nodes_from(self, other_watchpoint, deep_copy=False):
  171. """
  172. Copy nodes from other watchpoint.
  173. Args:
  174. other_watchpoint (Watchpoint): Other watchpoint.
  175. deep_copy (bool): Whether using deepcopy.
  176. """
  177. if deep_copy:
  178. self._watch_node = copy.deepcopy(other_watchpoint.nodes)
  179. else:
  180. self._watch_node = other_watchpoint.nodes
  181. def add_nodes(self, nodes):
  182. """Add node into watchpoint."""
  183. if not nodes:
  184. log.warning("Add empty nodes.")
  185. return
  186. if not isinstance(nodes, list):
  187. nodes = [nodes]
  188. for node in nodes:
  189. self._watch_node.add_node(node.name, node.type, node.full_name)
  190. def remove_nodes(self, nodes):
  191. """Remove nodes from watchpoint."""
  192. if not nodes:
  193. return
  194. if not isinstance(nodes, list):
  195. nodes = [nodes]
  196. for node in nodes:
  197. self._watch_node.remove_node(node.name)
  198. def get_node_status(self, node_name, node_type, full_name):
  199. """Judge if the node is in watch nodes."""
  200. if is_cst_type(node_type):
  201. return WatchNodeTree.INVALID
  202. scope_names = node_name.split('/')
  203. cur_node = self._watch_node
  204. status = 1
  205. for scope_name in scope_names:
  206. cur_node = cur_node.get(scope_name)
  207. if cur_node is None:
  208. status = WatchNodeTree.NOT_WATCH
  209. break
  210. if cur_node.watch_status == WatchNodeTree.TOTAL_WATCH:
  211. status = WatchNodeTree.TOTAL_WATCH
  212. break
  213. if status == WatchNodeTree.TOTAL_WATCH and cur_node.node_name != node_name:
  214. self._watch_node.add_node(node_name, node_type, full_name)
  215. return status
  216. def _get_watch_node(self, cur_watch_node, watch_node_list):
  217. """
  218. Traverse the watch nodes and add total watched node list to `watch_node_list`.
  219. Args:
  220. cur_watch_node (WatchNodeTree): The current watch node.
  221. watch_node_list (list[NodeBasicInfo]): The list of watch node basic infos.
  222. """
  223. if cur_watch_node.watch_status == WatchNodeTree.TOTAL_WATCH:
  224. node_info = NodeBasicInfo(name=cur_watch_node.node_name,
  225. full_name=cur_watch_node.full_name,
  226. type=cur_watch_node.node_type)
  227. watch_node_list.append(node_info)
  228. return
  229. for _, watch_node in cur_watch_node.get_children():
  230. self._get_watch_node(watch_node, watch_node_list)
  231. def get_watch_nodes(self):
  232. """
  233. Get the name of all total watched nodes.
  234. Returns:
  235. list[NodeBasicInfo], the list of watch node basic infos.
  236. """
  237. watch_nodes = []
  238. self._get_watch_node(self._watch_node, watch_nodes)
  239. return watch_nodes
  240. def get_pending_cmd(self, watch_nodes):
  241. """Return the watchpoint in proto format."""
  242. # construct SetCMD
  243. condition_id = self._condition.get('id')
  244. set_cmd = SetCMD()
  245. set_cmd.id = self._id
  246. set_cmd.delete = False
  247. set_cmd.watch_condition.condition = WATCHPOINT_CONDITION_MAPPING.get(condition_id)
  248. condition_mgr = ConditionMgr()
  249. condition = condition_mgr.get_condition(condition_id)
  250. param_dict = {
  251. param.get('name'): param for param in self._condition.get('params')
  252. }
  253. for param_name in condition.ordered_parameter_names:
  254. param = param_dict.get(param_name)
  255. if param:
  256. param_proto = set_cmd.watch_condition.params.add()
  257. param_proto.name = param.get('name')
  258. param_proto.value = param.get('value')
  259. param_proto.disabled = False
  260. # Only one parameter of condition in old mindspore version.
  261. set_cmd.watch_condition.value = param.get('value')
  262. else:
  263. param_proto = set_cmd.watch_condition.params.add()
  264. param_proto.name = param_name
  265. param_proto.disabled = True
  266. for watch_node in watch_nodes:
  267. event_node = set_cmd.watch_nodes.add()
  268. event_node.node_name = watch_node.full_name
  269. event_node.node_type = watch_node.type
  270. return set_cmd
  271. def get_watch_condition_info(self):
  272. """Get watch condition info."""
  273. watchpoint_info = {
  274. 'id': self._id,
  275. 'watch_condition': self._condition
  276. }
  277. if self.name:
  278. watchpoint_info['name'] = self.name
  279. return watchpoint_info
  280. class WatchpointHit:
  281. """The watchpoint hit structure."""
  282. def __init__(self, tensor_proto, watchpoint, node_name, graph_name):
  283. self._full_name = tensor_proto.node_name
  284. self._watchpoint = watchpoint
  285. self.node_name = node_name
  286. self.slot = tensor_proto.slot
  287. self.graph_name = graph_name
  288. self.error_code = 0
  289. @property
  290. def tensor_full_name(self):
  291. """The property of tensor full name."""
  292. tensor_name = ':'.join([self._full_name, self.slot])
  293. return tensor_name
  294. @property
  295. def watchpoint(self):
  296. """The property of watchpoint."""
  297. watchpoint = self._watchpoint.get_watch_condition_info()
  298. return watchpoint
  299. def __eq__(self, other):
  300. """Define the equal condition."""
  301. flag = self.tensor_full_name == other.tensor_full_name \
  302. and self.watchpoint == other.watchpoint \
  303. and self.graph_name == other.graph_name
  304. return flag