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

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