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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. def update_metadata(self, node_type, full_name, watch_status):
  76. """Update the metadata for watched node."""
  77. self._full_name = full_name
  78. self._node_type = self._translate_node_type(node_type)
  79. self._watch_status = watch_status
  80. @staticmethod
  81. def _translate_node_type(node_type):
  82. """Translate node type to watch node type."""
  83. flag = node_type
  84. if not node_type or is_scope_type(node_type):
  85. flag = 'scope'
  86. return flag
  87. def get(self, sub_name):
  88. """Get sub node."""
  89. return self._children.get(sub_name)
  90. def get_children(self):
  91. """Get all children."""
  92. for name_scope, sub_watch_node in self._children.items():
  93. yield name_scope, sub_watch_node
  94. def add_node(self, node_name, node_type, full_name=''):
  95. """
  96. Add watch node to watch node tree.
  97. Args:
  98. node_name (str): The node name.
  99. node_type (str): The node type.
  100. full_name (str): The full name of node.
  101. """
  102. log.debug("Add node %s with type: %s, full_name: %s", node_name, node_type, full_name)
  103. scope_names = node_name.split('/', 1)
  104. if len(scope_names) == 1:
  105. target_node = self.get(node_name)
  106. if not target_node:
  107. self.add(node_name, node_type, full_name, watch_status=WatchNodeTree.TOTAL_WATCH)
  108. else:
  109. target_node.update_metadata(node_type, full_name, WatchNodeTree.TOTAL_WATCH)
  110. return
  111. scope_name, sub_names = scope_names
  112. sub_tree = self.get(scope_name)
  113. if not sub_tree:
  114. sub_tree = self.add(scope_name, watch_status=1)
  115. sub_tree.add_node(sub_names, node_type, full_name)
  116. def add(self, name, node_type=None, full_name='', watch_status=1):
  117. """Add sub WatchPointTree."""
  118. sub_name = '/'.join([self._node_name, name]) if self._node_name else name
  119. sub_tree = WatchNodeTree(sub_name, node_type, full_name, watch_status)
  120. self._children[name] = sub_tree
  121. return sub_tree
  122. def remove_node(self, node_name):
  123. """Remove sub node from current tree."""
  124. log.debug("Remove %s", node_name)
  125. scope_names = node_name.split('/', 1)
  126. sub_tree_name = scope_names[0]
  127. sub_tree = self._children.get(sub_tree_name)
  128. if not sub_tree:
  129. log.error("Failed to find node %s in WatchNodeTree.", sub_tree_name)
  130. raise DebuggerParamValueError("Failed to find node {}".format(sub_tree_name))
  131. if len(scope_names) > 1:
  132. sub_tree.remove_node(scope_names[1])
  133. if sub_tree.watch_status == WatchNodeTree.NOT_WATCH or len(scope_names) == 1:
  134. self._children.pop(sub_tree_name)
  135. self._watch_status = WatchNodeTree.PARTIAL_WATCH if self._children else \
  136. WatchNodeTree.NOT_WATCH
  137. class Watchpoint:
  138. """
  139. The class of watchpoint stream.
  140. Args:
  141. watchpoint_id (int): The id of Watchpoint.
  142. watch_condition (dict): The condition of Watchpoint.
  143. - condition (str): Accept `INF` or `NAN`.
  144. - param (list[float]): Not defined yet.
  145. """
  146. def __init__(self, watchpoint_id, watch_condition, name=None):
  147. self._id = watchpoint_id
  148. self._condition = watch_condition
  149. self._watch_node = WatchNodeTree()
  150. self.name = name
  151. @property
  152. def watchpoint_id(self):
  153. """The property of watchpoint id."""
  154. return self._id
  155. @property
  156. def nodes(self):
  157. """The property of watch nodes."""
  158. return self._watch_node
  159. @property
  160. def condition(self):
  161. """The property of watch condition."""
  162. return self._condition
  163. def copy_nodes_from(self, other_watchpoint, deep_copy=False):
  164. """
  165. Copy nodes from other watchpoint.
  166. Args:
  167. other_watchpoint (Watchpoint): Other watchpoint.
  168. deep_copy (bool): Whether using deepcopy.
  169. """
  170. if deep_copy:
  171. self._watch_node = copy.deepcopy(other_watchpoint.nodes)
  172. else:
  173. self._watch_node = other_watchpoint.nodes
  174. def add_nodes(self, nodes):
  175. """Add node into watchpoint."""
  176. if not nodes:
  177. log.warning("Add empty nodes.")
  178. return
  179. if not isinstance(nodes, list):
  180. nodes = [nodes]
  181. for node in nodes:
  182. self._watch_node.add_node(node.name, node.type, node.full_name)
  183. def remove_nodes(self, nodes):
  184. """Remove nodes from watchpoint."""
  185. if not nodes:
  186. return
  187. if not isinstance(nodes, list):
  188. nodes = [nodes]
  189. for node in nodes:
  190. self._watch_node.remove_node(node.name)
  191. def get_node_status(self, node_name, node_type, full_name):
  192. """Judge if the node is in watch nodes."""
  193. if is_cst_type(node_type):
  194. return WatchNodeTree.INVALID
  195. scope_names = node_name.split('/')
  196. cur_node = self._watch_node
  197. status = 1
  198. for scope_name in scope_names:
  199. cur_node = cur_node.get(scope_name)
  200. if cur_node is None:
  201. status = WatchNodeTree.NOT_WATCH
  202. break
  203. if cur_node.watch_status == WatchNodeTree.TOTAL_WATCH:
  204. status = WatchNodeTree.TOTAL_WATCH
  205. break
  206. if status == WatchNodeTree.TOTAL_WATCH and cur_node.node_name != node_name:
  207. self._watch_node.add_node(node_name, node_type, full_name)
  208. return status
  209. def _get_watch_node(self, cur_watch_node, watch_node_list):
  210. """
  211. Traverse the watch nodes and add total watched node list to `watch_node_list`.
  212. Args:
  213. cur_watch_node (WatchNodeTree): The current watch node.
  214. watch_node_list (list[NodeBasicInfo]): The list of watch node basic infos.
  215. """
  216. if cur_watch_node.watch_status == WatchNodeTree.TOTAL_WATCH:
  217. node_info = NodeBasicInfo(name=cur_watch_node.node_name,
  218. full_name=cur_watch_node.full_name,
  219. type=cur_watch_node.node_type)
  220. watch_node_list.append(node_info)
  221. return
  222. for _, watch_node in cur_watch_node.get_children():
  223. self._get_watch_node(watch_node, watch_node_list)
  224. def get_watch_nodes(self):
  225. """
  226. Get the name of all total watched nodes.
  227. Returns:
  228. list[NodeBasicInfo], the list of watch node basic infos.
  229. """
  230. watch_nodes = []
  231. self._get_watch_node(self._watch_node, watch_nodes)
  232. return watch_nodes
  233. def get_pending_cmd(self, watch_nodes):
  234. """Return the watchpoint in proto format."""
  235. # construct SetCMD
  236. condition_id = self._condition.get('id')
  237. set_cmd = SetCMD()
  238. set_cmd.id = self._id
  239. set_cmd.delete = False
  240. set_cmd.watch_condition.condition = WATCHPOINT_CONDITION_MAPPING.get(condition_id)
  241. condition_mgr = ConditionMgr()
  242. condition = condition_mgr.get_condition(condition_id)
  243. param_dict = {
  244. param.get('name'): param for param in self._condition.get('params')
  245. }
  246. for param_name in condition.ordered_parameter_names:
  247. param = param_dict.get(param_name)
  248. if param:
  249. param_proto = set_cmd.watch_condition.params.add()
  250. param_proto.name = param.get('name')
  251. param_proto.value = param.get('value')
  252. param_proto.disabled = False
  253. # Only one parameter of condition in old mindspore version.
  254. set_cmd.watch_condition.value = param.get('value')
  255. else:
  256. param_proto = set_cmd.watch_condition.params.add()
  257. param_proto.name = param_name
  258. param_proto.disabled = True
  259. for watch_node in watch_nodes:
  260. event_node = set_cmd.watch_nodes.add()
  261. event_node.node_name = watch_node.full_name
  262. event_node.node_type = watch_node.type
  263. return set_cmd
  264. def get_watch_condition_info(self):
  265. """Get watch condition info."""
  266. watchpoint_info = {
  267. 'id': self._id,
  268. 'watch_condition': self._condition
  269. }
  270. if self.name:
  271. watchpoint_info['name'] = self.name
  272. return watchpoint_info
  273. class WatchpointHit:
  274. """The watchpoint hit structure."""
  275. def __init__(self, tensor_proto, watchpoint, node_name, graph_name):
  276. self._full_name = tensor_proto.node_name
  277. self._watchpoint = watchpoint
  278. self.node_name = node_name
  279. self.slot = tensor_proto.slot
  280. self.graph_name = graph_name
  281. self.error_code = 0
  282. @property
  283. def tensor_full_name(self):
  284. """The property of tensor full name."""
  285. tensor_name = ':'.join([self._full_name, self.slot])
  286. return tensor_name
  287. @property
  288. def watchpoint(self):
  289. """The property of watchpoint."""
  290. watchpoint = self._watchpoint.get_watch_condition_info()
  291. return watchpoint
  292. def __eq__(self, other):
  293. """Define the equal condition."""
  294. flag = self.tensor_full_name == other.tensor_full_name \
  295. and self.watchpoint == other.watchpoint \
  296. and self.graph_name == other.graph_name
  297. return flag