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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. from mindinsight.debugger.conditionmgr.common.utils import NodeBasicInfo
  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.proto.debug_grpc_pb2 import SetCMD, WatchCondition
  21. from mindinsight.debugger.conditionmgr.condition import ConditionIdEnum
  22. WATCHPOINT_CONDITION_MAPPING = {
  23. ConditionIdEnum.NAN.value: WatchCondition.Condition.nan,
  24. ConditionIdEnum.INF.value: WatchCondition.Condition.inf,
  25. ConditionIdEnum.OVERFLOW_ASCEND_CHIP.value: WatchCondition.Condition.overflow,
  26. ConditionIdEnum.MAX_GT.value: WatchCondition.Condition.max_gt,
  27. ConditionIdEnum.MAX_LT.value: WatchCondition.Condition.max_lt,
  28. ConditionIdEnum.MIN_GT.value: WatchCondition.Condition.min_gt,
  29. ConditionIdEnum.MIN_LT.value: WatchCondition.Condition.min_lt,
  30. ConditionIdEnum.MAX_MIN_GT.value: WatchCondition.Condition.max_min_gt,
  31. ConditionIdEnum.MAX_MIN_LT.value: WatchCondition.Condition.max_min_lt,
  32. ConditionIdEnum.MEAN_GT.value: WatchCondition.Condition.mean_gt,
  33. ConditionIdEnum.MEAN_LT.value: WatchCondition.Condition.mean_lt,
  34. ConditionIdEnum.TENSOR_OVERFLOW.value: WatchCondition.Condition.tensor_general_overflow,
  35. ConditionIdEnum.WEIGHT_OVERFLOW.value: WatchCondition.Condition.tensor_general_overflow,
  36. ConditionIdEnum.OPERATOR_OVERFLOW.value: WatchCondition.Condition.overflow,
  37. ConditionIdEnum.TENSOR_INITIALIZATION.value: WatchCondition.Condition.tensor_initialization,
  38. ConditionIdEnum.WEIGHT_INITIALIZATION.value: WatchCondition.Condition.tensor_initialization,
  39. ConditionIdEnum.TENSOR_TOO_LARGE.value: WatchCondition.Condition.tensor_too_large,
  40. ConditionIdEnum.WEIGHT_TOO_LARGE.value: WatchCondition.Condition.tensor_too_large,
  41. ConditionIdEnum.GRADIENT_TOO_LARGE.value: WatchCondition.Condition.tensor_too_large,
  42. ConditionIdEnum.GRADIENT_EXPLODING.value: WatchCondition.Condition.tensor_general_overflow,
  43. ConditionIdEnum.TENSOR_TOO_SMALL.value: WatchCondition.Condition.tensor_too_small,
  44. ConditionIdEnum.WEIGHT_TOO_SMALL.value: WatchCondition.Condition.tensor_too_small,
  45. ConditionIdEnum.GRADIENT_VANISHING.value: WatchCondition.Condition.tensor_too_small,
  46. ConditionIdEnum.TENSOR_ALL_ZERO.value: WatchCondition.Condition.tensor_all_zero,
  47. ConditionIdEnum.WEIGHT_CHANGE_TOO_LARGE.value: WatchCondition.Condition.tensor_change_too_large,
  48. ConditionIdEnum.WEIGHT_CHANGE_TOO_SMALL.value: WatchCondition.Condition.tensor_change_too_small,
  49. ConditionIdEnum.WEIGHT_NOT_CHANGED.value: WatchCondition.Condition.tensor_not_changed
  50. }
  51. class WatchNodeTree:
  52. """The WatchNode Node Structure."""
  53. NOT_WATCH = 0 # the scope node and the nodes below are not watched
  54. PARTIAL_WATCH = 1 # at least one node under the scope node is not watched
  55. TOTAL_WATCH = 2 # the scope node and the nodes below are all watched
  56. def __init__(self, node_name='', node_type=None, full_name='', watch_status=1):
  57. self._node_name = node_name
  58. self._full_name = full_name
  59. self._node_type = self._translate_node_type(node_type)
  60. self._watch_status = watch_status
  61. self._children = {}
  62. @property
  63. def node_name(self):
  64. """The property of node name."""
  65. return self._node_name
  66. @property
  67. def full_name(self):
  68. """The property of node name."""
  69. return self._full_name
  70. @property
  71. def node_type(self):
  72. """The property of node type."""
  73. return self._node_type
  74. @node_type.setter
  75. def node_type(self, value):
  76. """Set the node type."""
  77. self._node_type = self._translate_node_type(value)
  78. @property
  79. def watch_status(self):
  80. """The property of watch status about current node."""
  81. return self._watch_status
  82. def update_metadata(self, node_type, full_name, watch_status):
  83. """Update the metadata for watched node."""
  84. self._full_name = full_name
  85. self._node_type = self._translate_node_type(node_type)
  86. self._watch_status = watch_status
  87. @staticmethod
  88. def _translate_node_type(node_type):
  89. """Translate node type to watch node type."""
  90. flag = node_type
  91. if not node_type or is_scope_type(node_type):
  92. flag = 'scope'
  93. return flag
  94. def get(self, sub_name):
  95. """Get sub node."""
  96. return self._children.get(sub_name)
  97. def get_children(self):
  98. """Get all childrens."""
  99. for name_scope, sub_watch_node in self._children.items():
  100. yield name_scope, sub_watch_node
  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):
  154. self._id = watchpoint_id
  155. self._condition = watch_condition
  156. self._watch_node = WatchNodeTree()
  157. @property
  158. def watchpoint_id(self):
  159. """The property of watchpoint id."""
  160. return self._id
  161. @property
  162. def nodes(self):
  163. """The property of watch nodes."""
  164. return self._watch_node
  165. @property
  166. def condition(self):
  167. """The property of watch condition."""
  168. return self._condition
  169. def copy_nodes_from(self, other_watchpoint):
  170. """
  171. Copy nodes from other watchpoint.
  172. Args:
  173. other_watchpoint (Watchpoint): Other watchpoint.
  174. """
  175. self._watch_node = other_watchpoint.nodes
  176. def add_nodes(self, nodes):
  177. """Add node into watchpoint."""
  178. if not nodes:
  179. log.warning("Add empty nodes.")
  180. return
  181. if not isinstance(nodes, list):
  182. nodes = [nodes]
  183. for node in nodes:
  184. self._watch_node.add_node(node.name, node.type, node.full_name)
  185. def remove_nodes(self, nodes):
  186. """Remove nodes from watchpoint."""
  187. if not nodes:
  188. return
  189. if not isinstance(nodes, list):
  190. nodes = [nodes]
  191. for node in nodes:
  192. self._watch_node.remove_node(node.name)
  193. def get_node_status(self, node_name, node_type, full_name):
  194. """Judge if the node is in watch nodes."""
  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. set_cmd = SetCMD()
  237. set_cmd.id = self._id
  238. set_cmd.delete = False
  239. set_cmd.watch_condition.condition = WATCHPOINT_CONDITION_MAPPING.get(
  240. self._condition.get('id'))
  241. for param in self._condition.get('params'):
  242. # at most one param is provided
  243. param_proto = set_cmd.watch_condition.params.add()
  244. param_proto.name = param.get('name')
  245. param_proto.value = param.get('value')
  246. param_proto.disabled = False
  247. # Only one parameter of condition in current version.
  248. set_cmd.watch_condition.value = param.get('value')
  249. for watch_node in watch_nodes:
  250. event_node = set_cmd.watch_nodes.add()
  251. event_node.node_name = watch_node.full_name
  252. event_node.node_type = watch_node.type
  253. return set_cmd
  254. def get_watch_condition_info(self):
  255. """Get watch condition info."""
  256. watchpoint_info = {
  257. 'id': self._id,
  258. 'watch_condition': self._condition
  259. }
  260. return watchpoint_info
  261. class WatchpointHit:
  262. """The watchpoint hit structure."""
  263. def __init__(self, tensor_proto, watchpoint, node_name, graph_name):
  264. self._full_name = tensor_proto.node_name
  265. self._watchpoint = watchpoint
  266. self.node_name = node_name
  267. self.slot = tensor_proto.slot
  268. self.graph_name = graph_name
  269. self.error_code = 0
  270. @property
  271. def tensor_full_name(self):
  272. """The property of tensor full name."""
  273. tensor_name = ':'.join([self._full_name, self.slot])
  274. return tensor_name
  275. @property
  276. def watchpoint(self):
  277. """The property of watchpoint."""
  278. watchpoint = self._watchpoint.get_watch_condition_info()
  279. return watchpoint
  280. def __eq__(self, other):
  281. """Define the equal condition."""
  282. flag = self.tensor_full_name == other.tensor_full_name \
  283. and self.watchpoint == other.watchpoint \
  284. and self.graph_name == other.graph_name
  285. return flag