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.

recommender.py 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. """
  16. Predefined watchpoints.
  17. This module predefine recommend watchpoints.
  18. """
  19. import math
  20. import queue as Queue
  21. from mindinsight.debugger.conditionmgr.conditionmgr import ConditionMgr
  22. from mindinsight.debugger.conditionmgr.condition import TargetTypeEnum
  23. from mindinsight.debugger.conditionmgr.condition import ConditionIdEnum
  24. from mindinsight.debugger.conditionmgr.condition import ActivationFuncEnum
  25. from mindinsight.debugger.conditionmgr.common.utils import NodeBasicInfo
  26. from mindinsight.debugger.conditionmgr.log import logger
  27. from mindinsight.conf import settings
  28. UNSELECTED_STATUS = 0
  29. HALF_SELECTED_STATUS = 1
  30. SELECTED_STATUS = 2
  31. class _WatchPointData:
  32. """
  33. WatchPoint data container
  34. Args:
  35. watch_condition (dict): The dict of watch conditions.
  36. watch_nodes (list[NodeBasicInfo]): The list of node basic info.
  37. name (str): The name of watchpoint.
  38. """
  39. def __init__(self, watch_condition, watch_nodes, name):
  40. self.watch_condition = watch_condition
  41. self.watch_nodes = watch_nodes
  42. self.name = name
  43. def get_watch_condition_dict(self):
  44. return {
  45. "id": self.watch_condition.get("condition"),
  46. "params": [{
  47. "name": param.get_parameter_name(),
  48. "value": param.value
  49. } for param in self.watch_condition.get("params")]
  50. }
  51. class _ConditionParameterValue:
  52. """Condition parameter data container"""
  53. def __init__(self, parameter, value):
  54. self.parameter = parameter
  55. self.value = value
  56. def get_parameter_name(self):
  57. return self.parameter.name
  58. def recommend_watchpoints(condition_mgr: ConditionMgr, graph_stream, condition_context):
  59. """
  60. Recommend watchpoints.
  61. Args:
  62. condition_mgr (ConditionMgr): Condition manager instance.
  63. graph_stream (GraphHandler): Graph handler instance.
  64. condition_context (ConditionContext): Context for condition.
  65. Returns:
  66. list[WatchPointData], watch points to be created.
  67. """
  68. watch_points = []
  69. if not graph_stream.graph:
  70. logger.warning("Given graph is None.")
  71. return watch_points
  72. if not settings.ENABLE_RECOMMENDED_WATCHPOINTS:
  73. return watch_points
  74. # add weight watch points
  75. merged_info = get_basic_node_info(TargetTypeEnum.WEIGHT.value, graph_stream)
  76. _recommend_weight_initialization(merged_info, condition_mgr, watch_points, condition_context)
  77. _recommend_weight_change_too_large(merged_info, condition_mgr, watch_points, condition_context)
  78. # Because we cannot identify trainable weights currently, weight_no_change and weight_change_too_small will not be
  79. # recommended.
  80. trainable_weight_nodes = []
  81. _recommend_weight_not_changed(condition_mgr, trainable_weight_nodes, watch_points, condition_context)
  82. _recommend_weight_change_too_small(condition_mgr, trainable_weight_nodes, watch_points, condition_context)
  83. # add gradient watch points
  84. merged_info = get_basic_node_info(TargetTypeEnum.GRADIENT.value, graph_stream)
  85. _recommend_gradient_vanishing(merged_info, condition_mgr, watch_points, condition_context)
  86. # add tensor watch points
  87. merged_info = get_basic_node_info(TargetTypeEnum.TENSOR.value, graph_stream)
  88. _recommend_operator_overflow(merged_info, condition_mgr, watch_points, condition_context)
  89. _recommend_tensor_overflow(merged_info, condition_mgr, watch_points, condition_context)
  90. _recommend_tensor_all_zero(merged_info, condition_mgr, watch_points, condition_context)
  91. # add activation watch points
  92. merged_info = get_basic_node_info(TargetTypeEnum.ACTIVATION.value, graph_stream, ActivationFuncEnum.TANH.value)
  93. _recommend_activation_range(merged_info, condition_mgr, watch_points, condition_context,
  94. ActivationFuncEnum.TANH.value)
  95. merged_info = get_basic_node_info(TargetTypeEnum.ACTIVATION.value, graph_stream, ActivationFuncEnum.SIGMOID.value)
  96. _recommend_activation_range(merged_info, condition_mgr, watch_points, condition_context,
  97. ActivationFuncEnum.SIGMOID.value)
  98. merged_info = get_basic_node_info(TargetTypeEnum.ACTIVATION.value, graph_stream, ActivationFuncEnum.RELU.value)
  99. _recommend_activation_range(merged_info, condition_mgr, watch_points, condition_context,
  100. ActivationFuncEnum.RELU.value)
  101. return watch_points
  102. def _recommend_tensor_all_zero(basic_info_nodes, condition_mgr, watch_points, condition_context):
  103. """Recommend tensor all zero watchpoint."""
  104. if not basic_info_nodes:
  105. return
  106. if not condition_mgr.has_condition(ConditionIdEnum.TENSOR_ALL_ZERO.value, condition_context):
  107. return
  108. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.TENSOR_ALL_ZERO.value)
  109. tensor_all_zero_watchpoint = _WatchPointData(
  110. watch_condition={
  111. "condition": condition.id,
  112. "params": [_ConditionParameterValue(
  113. parameter=condition.get_parameter_definition("zero_percentage_ge"),
  114. value=100 # set default value to 100
  115. )]
  116. },
  117. watch_nodes=basic_info_nodes.copy(),
  118. name='recommend_tensor_all_zero_watchpoint'
  119. )
  120. watch_points.append(tensor_all_zero_watchpoint)
  121. def _recommend_tensor_overflow(basic_info_nodes, condition_mgr, watch_points, condition_context):
  122. """Recommend tensor general overflow watchpoint."""
  123. if not basic_info_nodes:
  124. return
  125. if not condition_mgr.has_condition(ConditionIdEnum.TENSOR_OVERFLOW.value, condition_context):
  126. return
  127. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.TENSOR_OVERFLOW.value)
  128. overflow_watchpoint = _WatchPointData(
  129. watch_condition={
  130. "condition": condition.id,
  131. "params": []
  132. },
  133. watch_nodes=basic_info_nodes.copy(),
  134. name='recommend_tensor_overflow_watchpoint'
  135. )
  136. watch_points.append(overflow_watchpoint)
  137. def _recommend_operator_overflow(basic_info_nodes, condition_mgr, watch_points, condition_context):
  138. """Recommend tensor overflow watchpoint."""
  139. if not basic_info_nodes:
  140. return
  141. if not condition_mgr.has_condition(ConditionIdEnum.OPERATOR_OVERFLOW.value, condition_context):
  142. return
  143. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.OPERATOR_OVERFLOW.value)
  144. overflow_d_watchpoint = _WatchPointData(
  145. watch_condition={
  146. "condition": condition.id,
  147. "params": []
  148. },
  149. watch_nodes=basic_info_nodes.copy(),
  150. name='recommend_operator_overflow_watchpoint'
  151. )
  152. watch_points.append(overflow_d_watchpoint)
  153. def _recommend_gradient_vanishing(basic_info_nodes, condition_mgr, watch_points, condition_context):
  154. """Recommend gradient vanishing watchpoint."""
  155. if not basic_info_nodes:
  156. return
  157. if not condition_mgr.has_condition(ConditionIdEnum.GRADIENT_VANISHING.value, condition_context):
  158. return
  159. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.GRADIENT_VANISHING.value)
  160. gradient_vanishing_watchpoint = _WatchPointData(
  161. watch_condition={
  162. "condition": condition.id,
  163. "params": [_ConditionParameterValue(
  164. parameter=condition.get_parameter_definition("abs_mean_lt"),
  165. value=1e-9 # set default value to 1e-9
  166. )]
  167. },
  168. watch_nodes=basic_info_nodes.copy(),
  169. name='recommend_gradient_vanishing_watchpoint'
  170. )
  171. watch_points.append(gradient_vanishing_watchpoint)
  172. def _recommend_weight_change_too_small(condition_mgr, trainable_weight_nodes, watch_points, condition_context):
  173. """Recommend weight change too small watchpoint."""
  174. if not trainable_weight_nodes:
  175. return
  176. if not condition_mgr.has_condition(ConditionIdEnum.WEIGHT_CHANGE_TOO_SMALL.value, condition_context):
  177. return
  178. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.WEIGHT_CHANGE_TOO_SMALL.value)
  179. weight_change_too_small_watchpoint = _WatchPointData(
  180. watch_condition={
  181. "condition": condition.id,
  182. "params": [
  183. _ConditionParameterValue(
  184. parameter=condition.get_parameter_definition("abs_mean_update_ratio_lt"),
  185. value=1.0e-4 # set default value to 1.0e-4
  186. ),
  187. ]
  188. },
  189. watch_nodes=trainable_weight_nodes,
  190. name='recommend_weight_change_too_small_watchpoint'
  191. )
  192. watch_points.append(weight_change_too_small_watchpoint)
  193. def _recommend_weight_not_changed(condition_mgr, trainable_weight_nodes, watch_points, condition_context):
  194. """Recommend weight not changed watchpoint."""
  195. if not trainable_weight_nodes:
  196. return
  197. if not condition_mgr.has_condition(ConditionIdEnum.WEIGHT_NOT_CHANGED.value, condition_context):
  198. return
  199. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.WEIGHT_NOT_CHANGED.value)
  200. weight_no_change_watchpoint = _WatchPointData(
  201. watch_condition={
  202. "condition": condition.id,
  203. "params": [
  204. _ConditionParameterValue(
  205. parameter=condition.get_parameter_definition("rtol"),
  206. value=1.0e-5 # set default value to 1.0e-5
  207. ),
  208. _ConditionParameterValue(
  209. parameter=condition.get_parameter_definition("atol"),
  210. value=1.0e-8 # set default value to 1.0e-8
  211. ),
  212. ]
  213. },
  214. watch_nodes=trainable_weight_nodes,
  215. name='recommend_weight_not_changed_watchpoint'
  216. )
  217. watch_points.append(weight_no_change_watchpoint)
  218. def _recommend_weight_change_too_large(basic_info_nodes, condition_mgr, watch_points, condition_context):
  219. """Recommend weight change too large watchpoint."""
  220. if not basic_info_nodes:
  221. return
  222. if not condition_mgr.has_condition(ConditionIdEnum.WEIGHT_CHANGE_TOO_LARGE.value, condition_context):
  223. return
  224. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.WEIGHT_CHANGE_TOO_LARGE.value)
  225. weight_initialization_watchpoint = _WatchPointData(
  226. watch_condition={
  227. "condition": condition.id,
  228. "params": [_ConditionParameterValue(
  229. parameter=condition.get_parameter_definition("abs_mean_update_ratio_gt"),
  230. value=1 # set default value to 1
  231. )]
  232. },
  233. watch_nodes=basic_info_nodes.copy(),
  234. name='recommend_weight_change_too_large_watchpoint'
  235. )
  236. watch_points.append(weight_initialization_watchpoint)
  237. def _recommend_weight_initialization(basic_info_nodes, condition_mgr, watch_points, condition_context):
  238. """Recommend weight initialization watchpoint."""
  239. if not basic_info_nodes:
  240. return
  241. if not condition_mgr.has_condition(ConditionIdEnum.WEIGHT_INITIALIZATION.value, condition_context):
  242. return
  243. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.WEIGHT_INITIALIZATION.value)
  244. weight_initialization_watchpoint = _WatchPointData(
  245. watch_condition={
  246. "condition": condition.id,
  247. "params": [_ConditionParameterValue(
  248. parameter=condition.get_parameter_definition("zero_percentage_ge"),
  249. value=100 # set default value to 100
  250. )]
  251. },
  252. watch_nodes=basic_info_nodes.copy(),
  253. name='recommend_weight_initialization_watchpoint'
  254. )
  255. watch_points.append(weight_initialization_watchpoint)
  256. def _recommend_activation_range(basic_info_nodes, condition_mgr, watch_points, condition_context, activation_func):
  257. """Recommend activation range watchpoint."""
  258. if not basic_info_nodes:
  259. return
  260. if not condition_mgr.has_condition(ConditionIdEnum.ACTIVATION_RANGE.value, condition_context):
  261. return
  262. condition = condition_mgr.get_condition(condition_id=ConditionIdEnum.ACTIVATION_RANGE.value)
  263. params = _get_recommend_activation_params(condition, activation_func)
  264. activation_range_watchpoint = _WatchPointData(
  265. watch_condition={
  266. "condition": condition.id,
  267. "params": params
  268. },
  269. watch_nodes=basic_info_nodes.copy(),
  270. name='recommend_{}_activation_range_watchpoint'.format(activation_func.lower())
  271. )
  272. watch_points.append(activation_range_watchpoint)
  273. def get_basic_node_info(node_category, graph_stream, activation_func=None):
  274. """Get node merged info."""
  275. basic_info_nodes = _get_basic_node_info_by_node_category(node_category, graph_stream, activation_func)
  276. merged_info = _merge_nodes(basic_info_nodes, graph_stream.whole_graph)
  277. merged_info = _add_graph_name(merged_info, graph_stream)
  278. return merged_info
  279. def _get_basic_node_info_by_node_category(node_category, graph_stream, activation_func=None):
  280. """Get node basic info by node category."""
  281. pattern = {'node_category': node_category}
  282. if activation_func:
  283. pattern['condition'] = {'activation_func': activation_func}
  284. all_graph_nodes = graph_stream.search_in_graph(pattern)
  285. return all_graph_nodes
  286. def _merge_nodes(leaf_nodes, graph):
  287. """merge nodes in one graph"""
  288. unmerged_tree = graph.get_nodes(leaf_nodes)
  289. tmp_node_queue = Queue.Queue()
  290. # watch node list in layer order
  291. watch_nodes = []
  292. for node in unmerged_tree:
  293. if node["type"] != "name_scope":
  294. # if node is leaf_node, it is totally chosen
  295. node["status"] = SELECTED_STATUS
  296. else:
  297. # if node is not leaf_node, it is not chosen initially
  298. node["status"] = UNSELECTED_STATUS
  299. tmp_node_queue.put(node)
  300. while not tmp_node_queue.empty():
  301. cur_node = tmp_node_queue.get()
  302. watch_nodes.append(cur_node)
  303. for sub_node in cur_node["nodes"]:
  304. if sub_node["type"] != "name_scope":
  305. # if node is leaf_node, it is totally chosen
  306. sub_node["status"] = SELECTED_STATUS
  307. else:
  308. # if node is not leaf_node, it is not chosen initially
  309. sub_node["status"] = UNSELECTED_STATUS
  310. tmp_node_queue.put(sub_node)
  311. merged_watch_nodes = []
  312. while watch_nodes:
  313. cur_node = watch_nodes.pop()
  314. node_name = cur_node["name"]
  315. sub_count = graph.normal_node_map.get(node_name).subnode_count
  316. if len(cur_node["nodes"]) < sub_count:
  317. continue
  318. is_all_chosen = True
  319. for sub_node in cur_node["nodes"]:
  320. if sub_node["status"] != SELECTED_STATUS:
  321. is_all_chosen = False
  322. break
  323. if is_all_chosen:
  324. cur_node["status"] = SELECTED_STATUS
  325. merged_watch_nodes.append(cur_node)
  326. else:
  327. cur_node["status"] = HALF_SELECTED_STATUS
  328. logger.debug("merged_watch_nodes: %s", merged_watch_nodes)
  329. out_nodes = []
  330. for node_info in merged_watch_nodes:
  331. full_name = graph.get_full_name_by_node_name(node_info["name"])
  332. node_basic_info = NodeBasicInfo(name=node_info["name"], full_name=full_name, type=node_info["type"])
  333. out_nodes.append(node_basic_info)
  334. logger.debug("out_nodes: %s", out_nodes)
  335. return out_nodes
  336. def _add_graph_name(nodes, graph_stream):
  337. """add graph_name in node.name"""
  338. if len(graph_stream.graph) > 1:
  339. return nodes
  340. graph_name = graph_stream.graph_names[0]
  341. output_nodes = []
  342. for node in nodes:
  343. node_basic_info = graph_stream.construct_node_basic_info(
  344. full_name=node.full_name, graph_name=graph_name, node_name=node.name, node_type=node.type)
  345. output_nodes.append(node_basic_info)
  346. return output_nodes
  347. def _sigmoid(value):
  348. """calculate the sigmoid of value"""
  349. return 1.0 / (1.0 + math.exp(value))
  350. def _get_recommend_activation_params(condition, activation_func):
  351. """Get recommend params for tanh, sigmoid and relu activation function."""
  352. params = []
  353. if activation_func == ActivationFuncEnum.TANH.value:
  354. # The recommend params for Tanh: The percentage of value in range (tanh(-8.8), tanh(8.8)) is lower than 0.1%
  355. params = [
  356. _ConditionParameterValue(
  357. parameter=condition.get_parameter_definition("range_percentage_lt"),
  358. value=0.1
  359. ),
  360. _ConditionParameterValue(
  361. parameter=condition.get_parameter_definition("range_start_inclusive"),
  362. value=math.tanh(-8.8)
  363. ),
  364. _ConditionParameterValue(
  365. parameter=condition.get_parameter_definition("range_end_inclusive"),
  366. value=math.tanh(8.8)
  367. )]
  368. if activation_func == ActivationFuncEnum.SIGMOID.value:
  369. # The recommend params for Sigmoid:
  370. # The percentage of value in range (sigmoid(-16.2)), sigmoid(16.2)) is lower than 0.1%
  371. params = [
  372. _ConditionParameterValue(
  373. parameter=condition.get_parameter_definition("range_percentage_lt"),
  374. value=0.1
  375. ),
  376. _ConditionParameterValue(
  377. parameter=condition.get_parameter_definition("range_start_inclusive"),
  378. value=_sigmoid(-16.2)
  379. ),
  380. _ConditionParameterValue(
  381. parameter=condition.get_parameter_definition("range_end_inclusive"),
  382. value=_sigmoid(16.2)
  383. )]
  384. if activation_func == ActivationFuncEnum.RELU.value:
  385. # The recommend params for ReLU:
  386. # The percentage of value in range (-1, 0) is greater than 99.9%
  387. params = [
  388. _ConditionParameterValue(
  389. parameter=condition.get_parameter_definition("range_percentage_gt"),
  390. value=99.9
  391. ),
  392. _ConditionParameterValue(
  393. parameter=condition.get_parameter_definition("range_start_inclusive"),
  394. value=-1
  395. ),
  396. _ConditionParameterValue(
  397. parameter=condition.get_parameter_definition("range_end_inclusive"),
  398. value=0
  399. )]
  400. return params