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

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