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.

debugger_session.py 29 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. # Copyright 2020-2021 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. """Implement the debugger server."""
  16. from functools import wraps
  17. from mindinsight.datavisual.data_transform.graph import NodeTypeEnum
  18. from mindinsight.datavisual.utils.tools import to_float
  19. from mindinsight.debugger.common.exceptions.exceptions import DebuggerParamValueError, \
  20. DebuggerParamTypeError, DebuggerCompareTensorError, DebuggerTensorGraphError, \
  21. DebuggerTensorHitError, DebuggerSetRecommendWatchpointsError, MindInsightException
  22. from mindinsight.debugger.common.log import LOGGER as log
  23. from mindinsight.debugger.common.utils import ServerStatus, \
  24. create_view_event_from_tensor_basic_info, Streams
  25. from mindinsight.debugger.conditionmgr.condition import ConditionContext
  26. from mindinsight.debugger.conditionmgr.conditionmgr import ConditionMgr
  27. from mindinsight.debugger.conditionmgr.recommender import recommend_watchpoints
  28. from mindinsight.debugger.debugger_cache import DebuggerCache
  29. from mindinsight.debugger.debugger_services.debugger_server_factory import DebuggerServerFactory
  30. from mindinsight.debugger.stream_operator.tensor_detail_info import TensorDetailInfo
  31. from mindinsight.debugger.stream_operator.training_control_operator import TrainingControlOperator
  32. from mindinsight.debugger.stream_operator.watchpoint_operator import WatchpointOperator
  33. from mindinsight.utils.tensor import TensorUtils, MAX_DIMENSIONS_FOR_TENSOR
  34. def try_except(func):
  35. """Send latest metadata when catch exception."""
  36. @wraps(func)
  37. def send_latest_metadata(self, *args, **kwargs):
  38. try:
  39. return func(self, *args, **kwargs)
  40. except MindInsightException as err:
  41. metadata = self.cache_store.get_stream_handler(Streams.METADATA).get()
  42. self.cache_store.put_data(metadata)
  43. log.info("Put latest metadata into data-queue.")
  44. raise err
  45. return send_latest_metadata
  46. class DebuggerSession:
  47. """The server manager of debugger."""
  48. def __init__(self, context):
  49. self.condition_mgr = ConditionMgr()
  50. self.cache_store = DebuggerCache()
  51. self.context = context
  52. self.back_server = DebuggerServerFactory().get_debugger_server(self.cache_store, context)
  53. @property
  54. def train_job(self):
  55. """The property of train job."""
  56. return self.context.train_job
  57. def get_condition_collections(self, train_id=""):
  58. """Get default condition_collections"""
  59. metadata_stream = self.cache_store.get_stream_handler(Streams.METADATA)
  60. condition_context = ConditionContext(metadata_stream.backend, metadata_stream.step)
  61. log.debug("Train_id: %s, backend: %s", train_id, condition_context.backend)
  62. return self.condition_mgr.get_all_collections(condition_context)
  63. def set_recommended_watch_points(self, set_recommended, train_id=""):
  64. """Set recommended watch points."""
  65. if not isinstance(set_recommended, bool):
  66. log.error("Bool param should be given for set_recommended")
  67. raise DebuggerParamValueError("Bool param should be given.")
  68. metadata_stream = self.cache_store.get_stream_handler(Streams.METADATA)
  69. if metadata_stream.recommendation_confirmed:
  70. log.error("User has confirmed setting recommended watchpoints")
  71. raise DebuggerSetRecommendWatchpointsError()
  72. metadata_stream.recommendation_confirmed = True
  73. condition_context = ConditionContext(metadata_stream.backend, metadata_stream.step)
  74. log.debug("Train_id: %s, backend: %s", train_id, condition_context.backend)
  75. res = metadata_stream.get(['state', 'enable_recheck'])
  76. if set_recommended:
  77. res['id'] = self._add_recommended_watchpoints(condition_context)
  78. return res
  79. def _add_recommended_watchpoints(self, condition_context):
  80. """Add predefined watchpoints."""
  81. log.debug("Add predefined watchpoints.")
  82. multi_card_graph_stream = self.cache_store.get_stream_handler(Streams.GRAPH)
  83. watchpoints = recommend_watchpoints(self.condition_mgr, multi_card_graph_stream, condition_context)
  84. watch_point_stream_handler = self.cache_store.get_stream_handler(Streams.WATCHPOINT)
  85. device_stream = self.cache_store.get_stream_handler(Streams.DEVICE)
  86. watch_points_ids = []
  87. for watchpoint in watchpoints:
  88. watch_points_id = watch_point_stream_handler.create_watchpoint(
  89. watch_condition=watchpoint.get_watch_condition_dict(),
  90. watch_nodes=watchpoint.watch_nodes,
  91. name=watchpoint.name,
  92. condition_mgr=self.condition_mgr,
  93. device_amount=device_stream.device_amount
  94. )
  95. watch_points_ids.append(watch_points_id)
  96. return watch_points_ids
  97. def start(self):
  98. """Start server."""
  99. self.back_server.start()
  100. log.info("Start debugger backend server.")
  101. def _stop_handler(self, signum, frame):
  102. """Register stop server handler."""
  103. self.stop()
  104. log.debug("Deal with stop signal: %s, %s", signum, frame)
  105. def stop(self):
  106. """Stop debugger server."""
  107. log.info("Send terminate info to client.")
  108. self.control({'mode': 'terminate'})
  109. self.back_server.stop()
  110. log.info("Stop debugger server.")
  111. def poll_data(self, pos):
  112. """
  113. Get the pos-th data from DebuggerCache.
  114. Args:
  115. pos (int): The index of data.
  116. Returns:
  117. dict, the data to be updated.
  118. """
  119. if not isinstance(pos, str):
  120. log.error("Pos should be string. Received: %s", pos)
  121. raise DebuggerParamValueError("Pos should be string.")
  122. reply = self.cache_store.get_data(pos)
  123. return reply
  124. def search(self, filter_condition):
  125. """
  126. Search for single node in graph.
  127. Args:
  128. filter_condition (dict): Filter condition.
  129. - name (str): The name pattern.
  130. - graph_name (str): The graph name.
  131. - watch_point_id (int): The id of watchpoint. Default: 0.
  132. - node_category (str): The node_category. Default: None
  133. - rank_id (int): The id of rank. Default: 0.
  134. Returns:
  135. dict, the searched nodes.
  136. """
  137. log.info("receive search request with filter_condition: %s", filter_condition)
  138. # validate watchpoint id
  139. watch_point_id = filter_condition.pop('watch_point_id', 0)
  140. rank_id = filter_condition.pop('rank_id', 0)
  141. watchpoint_stream = self.cache_store.get_stream_handler(Streams.WATCHPOINT)
  142. watchpoint_stream.validate_watchpoint_id(watch_point_id)
  143. # validate and update graph name
  144. graph_stream = self.cache_store.get_stream_handler(Streams.GRAPH).get_graph_handler_by_rank_id(rank_id)
  145. graph_name = graph_stream.validate_graph_name(filter_condition.get('graph_name'))
  146. filter_condition['graph_name'] = graph_name
  147. # get searched graph
  148. graph = graph_stream.search_nodes(filter_condition)
  149. # add watched label to graph
  150. watchpoint_stream.set_watch_nodes(graph, graph_stream, watch_point_id, graph_name, rank_id)
  151. return graph
  152. def tensor_comparisons(self, name, shape, detail='data', tolerance='0', rank_id=0):
  153. """
  154. Get tensor comparisons data for given name, detail, shape and tolerance.
  155. Args:
  156. name (str): The name of tensor for ui.
  157. detail (str): Specify which data to query. Current available value is 'data' which means
  158. concrete tensor data. Histogram or unique count can be supported in the future.
  159. shape (str): Specify concrete dimensions of shape.
  160. tolerance (str): Specify tolerance of difference between current step tensor and previous
  161. step tensor. Default value is 0.
  162. rank_id (int): The id of rank. Default: 0.
  163. Raises:
  164. DebuggerParamValueError, If node type is not parameter or value of detail is not support.
  165. DebuggerCompareTensorError, If MindSpore is not in waiting state.
  166. Returns:
  167. dict, the retrieved data.
  168. """
  169. if self.cache_store.get_stream_handler(
  170. Streams.METADATA).state != ServerStatus.WAITING.value:
  171. log.error("Failed to compare tensors as the MindSpore is not in waiting state.")
  172. raise DebuggerCompareTensorError(
  173. "Failed to compare tensors as the MindSpore is not in waiting state."
  174. )
  175. self.validate_tensor_param(name, detail)
  176. # Limit to query max two dimensions for tensor in table view.
  177. parsed_shape = TensorUtils.parse_shape(shape, limit=MAX_DIMENSIONS_FOR_TENSOR)
  178. node_type, tensor_name = self._get_tensor_name_and_type_by_ui_name(name)
  179. tolerance = to_float(tolerance, 'tolerance')
  180. tensor_stream = self.cache_store.get_stream_handler(Streams.TENSOR).get_tensor_handler_by_rank_id(rank_id)
  181. cur_step = self.cache_store.get_stream_handler(Streams.METADATA).step
  182. if node_type == NodeTypeEnum.PARAMETER.value:
  183. reply = tensor_stream.get_tensors_diff(tensor_name, parsed_shape, tolerance, cur_step)
  184. else:
  185. raise DebuggerParamValueError(
  186. "The node type must be parameter, but got {}.".format(node_type))
  187. return reply
  188. def retrieve(self, mode, filter_condition=None):
  189. """
  190. Retrieve data according to mode and params.
  191. Args:
  192. mode (str): The type of info message.
  193. filter_condition (dict): The filter condition.
  194. Returns:
  195. dict, the retrieved data.
  196. """
  197. log.info("receive retrieve request for mode:%s\n, filter_condition: %s", mode,
  198. filter_condition)
  199. mode_mapping = {
  200. 'all': self._retrieve_all,
  201. 'node': self._retrieve_node,
  202. 'watchpoint': self._retrieve_watchpoint,
  203. }
  204. # validate param <mode>
  205. if mode not in mode_mapping.keys():
  206. log.error("Invalid param <mode>. <mode> should be in ['all', 'node', 'watchpoint', "
  207. "'watchpoint_hit'], but got %s.", mode_mapping)
  208. raise DebuggerParamValueError("Invalid mode.")
  209. # validate backend status
  210. metadata_stream = self.cache_store.get_stream_handler(Streams.METADATA)
  211. if metadata_stream.state == ServerStatus.PENDING.value:
  212. log.info("The backend is in pending status.")
  213. return metadata_stream.get()
  214. filter_condition = {} if filter_condition is None else filter_condition
  215. reply = mode_mapping[mode](filter_condition)
  216. return reply
  217. def _retrieve_all(self, filter_condition=None):
  218. """Retrieve metadata, root graph and watchpoint list."""
  219. if filter_condition:
  220. log.error("No filter condition required for retrieve all request.")
  221. raise DebuggerParamTypeError("filter_condition should be empty.")
  222. self.cache_store.clean_data()
  223. log.info("Clean data queue cache when retrieve all request.")
  224. result = {}
  225. for stream in [Streams.METADATA, Streams.GRAPH, Streams.DEVICE]:
  226. sub_res = self.cache_store.get_stream_handler(stream).get()
  227. result.update(sub_res)
  228. devices = result['devices']
  229. if not devices:
  230. graph = result['graph']
  231. metadata = result['metadata']
  232. device = {'rank_id': 0, 'server_ip': metadata.get('ip', 'localhost'),
  233. 'device_id': metadata.get('device_name', ''),
  234. 'graph_names': graph.get('graph_names', [])}
  235. devices.append(device)
  236. sub_res = self._hide_parameters_for_ui()
  237. result.update(sub_res)
  238. return result
  239. def _retrieve_node(self, filter_condition):
  240. """
  241. Retrieve node info.
  242. Args:
  243. filter_condition (dict): Filter condition.
  244. - name (str): The name of single node.
  245. - graph_name (str): The relative graph_name of the node.
  246. - single_node (bool): If False, return the sub-layer of single node. If True, return
  247. the node list from root node to single node.
  248. - watch_point_id (int): The id of watchpoint.
  249. Returns:
  250. dict, reply with graph.
  251. """
  252. log.debug("Retrieve node %s.", filter_condition)
  253. # validate node name
  254. node_name = filter_condition.get('name')
  255. rank_id = filter_condition.get('rank_id', 0)
  256. graph_stream = self.cache_store.get_stream_handler(Streams.GRAPH).get_graph_handler_by_rank_id(rank_id)
  257. graph_name = graph_stream.validate_graph_name(filter_condition.get('graph_name'))
  258. if node_name:
  259. # validate node name
  260. graph_stream.get_node_type(node_name, graph_name)
  261. filter_condition['single_node'] = bool(filter_condition.get('single_node'))
  262. filter_condition['graph_name'] = graph_name
  263. reply = self._get_nodes_info(filter_condition)
  264. return reply
  265. def _get_nodes_info(self, filter_condition):
  266. """
  267. Get nodes info.
  268. Args:
  269. filter_condition (dict): The filter condition.
  270. - name (str): The node name.
  271. - graph_name (str): The relative graph_name of the node.
  272. - single_node (bool): If False, return the sub-layer of single node. If True, return
  273. the node list from root node to single node.
  274. - watch_point_id (int): The id of watchpoint.
  275. Returns:
  276. dict, reply with graph.
  277. """
  278. # validate watch_point_id
  279. rank_id = filter_condition.get('rank_id', 0)
  280. watch_point_id = filter_condition.get('watch_point_id', 0)
  281. watchpoint_stream = self.cache_store.get_stream_handler(Streams.WATCHPOINT)
  282. watchpoint_stream.validate_watchpoint_id(watch_point_id)
  283. # get graph
  284. graph_stream = self.cache_store.get_stream_handler(Streams.GRAPH).get_graph_handler_by_rank_id(rank_id)
  285. reply = graph_stream.get(filter_condition)
  286. graph = reply.get('graph')
  287. # add watched label to graph
  288. watchpoint_stream.set_watch_nodes(graph, graph_stream, watch_point_id, filter_condition.get('graph_name'),
  289. rank_id)
  290. return reply
  291. def retrieve_tensor_history(self, node_name, graph_name=None, rank_id=0):
  292. """
  293. Retrieve tensor history for leaf node.
  294. Args:
  295. node_name (str): The name of leaf node.
  296. graph_name (str): The graph name. Default: None.
  297. rank_id (int): The id of rank. Default: 0.
  298. Returns:
  299. dict, the tensor history and metadata.
  300. """
  301. log.info("Retrieve tensor history for node: %s.", node_name)
  302. metadata_stream = self.cache_store.get_stream_handler(Streams.METADATA)
  303. if metadata_stream.state == ServerStatus.PENDING.value:
  304. log.info("The backend is in pending status.")
  305. return metadata_stream.get(['state', 'step'])
  306. res = self._get_tensor_history(node_name, graph_name, rank_id)
  307. return res
  308. def _get_tensor_history(self, node_name, graph_name=None, rank_id=0):
  309. """
  310. Get tensor history for single node.
  311. Args:
  312. node_name (str): The name of leaf node.
  313. graph_name (str): The graph name. Default: None.
  314. rank_id (int): The id of rank. Default: 0.
  315. Returns:
  316. dict, the tensor history and metadata.
  317. """
  318. # get basic tensor history
  319. graph_stream = self.cache_store.get_stream_handler(Streams.GRAPH).get_graph_handler_by_rank_id(rank_id)
  320. tensor_history = graph_stream.get_tensor_history(node_name, graph_name)
  321. # add tensor value for tensor history
  322. self._add_tensor_value_for_tensor_history(tensor_history, node_name, graph_name, rank_id)
  323. # add hit label for tensor history
  324. self.cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).update_tensor_history(tensor_history, rank_id)
  325. # add metadata
  326. metadata = self.cache_store.get_stream_handler(Streams.METADATA).get(['step'])
  327. tensor_history.update(metadata)
  328. return tensor_history
  329. def _add_tensor_value_for_tensor_history(self, tensor_history, node_name, graph_name, rank_id):
  330. """
  331. Add tensor value for_tensor_history and send ViewCMD if tensor value missed.
  332. Args:
  333. tensor_history (list[dict]): A list of tensor info, including name and type.
  334. node_name (str): The UI node name.
  335. graph_name (str): The graph name. Default: None.
  336. rank_id (int): The id of rank. Default: 0.
  337. Returns:
  338. dict, the tensor info.
  339. """
  340. tensor_stream = self.cache_store.get_stream_handler(Streams.TENSOR).get_tensor_handler_by_rank_id(rank_id)
  341. cur_step = self.cache_store.get_stream_handler(Streams.METADATA).step
  342. missed_tensors = tensor_stream.update_tensor_history(tensor_history, cur_step)
  343. if missed_tensors:
  344. view_cmd = create_view_event_from_tensor_basic_info(missed_tensors)
  345. self.cache_store.put_command(
  346. {'view_cmd': view_cmd, 'node_name': node_name, 'graph_name': graph_name, 'rank_id': rank_id})
  347. log.debug("Send view cmd.")
  348. def retrieve_tensor_value(self, name, detail, shape, graph_name=None, prev=False, rank_id=0):
  349. """Retrieve the tensor value."""
  350. log.info("Retrieve tensor value: name: %s, detail: %s, shape: %s", name, detail, shape)
  351. self.validate_tensor_param(name, detail)
  352. # Limit to query max two dimensions for tensor in table view.
  353. parsed_shape = TensorUtils.parse_shape(shape, limit=MAX_DIMENSIONS_FOR_TENSOR)
  354. node_type, tensor_name = self._get_tensor_name_and_type_by_ui_name(name, graph_name, rank_id)
  355. reply = self.cache_store.get_stream_handler(Streams.TENSOR).get(
  356. {'name': tensor_name,
  357. 'node_type': node_type,
  358. 'shape': parsed_shape,
  359. 'prev': prev},
  360. rank_id
  361. )
  362. reply['tensor_value']['name'] = name
  363. return reply
  364. def _get_tensor_name_and_type_by_ui_name(self, name, graph_name=None, rank_id=0):
  365. """
  366. Get inner tensor name and type by UI name.
  367. Args:
  368. name (str): Node name shown in UI.
  369. graph_name (Union[str, None]): The graph name, default is: None.
  370. rank_id (int): The id of rank. Default: 0.
  371. Returns:
  372. str, full name of tensor.
  373. str, node type of tensor.
  374. """
  375. node_name, slot = name.rsplit(':', 1)
  376. graph_stream = self.cache_store.get_stream_handler(Streams.GRAPH).get_graph_handler_by_rank_id(rank_id)
  377. graph_name = graph_name if graph_name else graph_stream.get_graph_id_by_name(node_name)
  378. node_type = graph_stream.get_node_type(node_name, graph_name)
  379. full_name = graph_stream.get_full_name(node_name, graph_name)
  380. tensor_name = full_name + ':' + slot
  381. return node_type, tensor_name
  382. @staticmethod
  383. def validate_tensor_param(name, detail):
  384. """Validate params for retrieve tensor request."""
  385. # validate name
  386. if not isinstance(name, str) or ':' not in name:
  387. log.error("Invalid tensor name. Received: %s", name)
  388. raise DebuggerParamValueError("Invalid tensor name.")
  389. # validate data
  390. if detail != 'data':
  391. log.error("Invalid detail value. Received: %s", detail)
  392. raise DebuggerParamValueError("Invalid detail value.")
  393. def _retrieve_watchpoint(self, filter_condition):
  394. """
  395. Retrieve watchpoint.
  396. Args:
  397. filter_condition (dict): Filter condition.
  398. - watch_point_id (int): The id of watchpoint. If not given, return all watchpoints.
  399. - name (str): The name of single node.
  400. - single_node (bool): If False, return the sub-layer of single node. If True, return
  401. the node list from root node to single node.
  402. Returns:
  403. dict, watch point list or relative graph.
  404. """
  405. watchpoint_id = filter_condition.get('watch_point_id', 0)
  406. if not watchpoint_id:
  407. reply = self._hide_parameters_for_ui()
  408. log.debug("Get condition of watchpoints.")
  409. else:
  410. reply = self._retrieve_node(filter_condition)
  411. log.debug("Get graph of %d-th watchpoint.", watchpoint_id)
  412. return reply
  413. def search_watchpoint_hits(self, group_condition):
  414. """
  415. Retrieve watchpoint hit.
  416. Args:
  417. group_condition (dict): Filter condition.
  418. - limit (int): The limit of each page.
  419. - offset (int): The offset of current page.
  420. - node_name (str): The retrieved node name.
  421. - graph_name (str): The retrieved graph name.
  422. - rank_id (int): The rank id.
  423. Returns:
  424. dict, watch point list or relative graph.
  425. """
  426. if not isinstance(group_condition, dict):
  427. log.error("Group condition for watchpoint-hits request should be a dict")
  428. raise DebuggerParamTypeError("Group condition for watchpoint-hits request should be a dict")
  429. metadata_stream = self.cache_store.get_stream_handler(Streams.METADATA)
  430. if metadata_stream.state == ServerStatus.PENDING.value:
  431. log.info("The backend is in pending status.")
  432. return metadata_stream.get()
  433. rank_id = group_condition.pop('rank_id', 0)
  434. reply = {}
  435. multi_watchpoint_hit_stream = self.cache_store.get_stream_handler(Streams.WATCHPOINT_HIT)
  436. if multi_watchpoint_hit_stream.check_rank_id(rank_id):
  437. watchpoint_hit_stream = multi_watchpoint_hit_stream.get_hit_handler_by_rank_id(rank_id)
  438. reply = watchpoint_hit_stream.group_by(group_condition)
  439. reply['outdated'] = self.cache_store.get_stream_handler(Streams.WATCHPOINT).is_recheckable()
  440. return reply
  441. def create_watchpoint(self, params):
  442. """
  443. Create watchpoint.
  444. Args:
  445. params (dict): Params for create watchpoint.
  446. - watch_condition (dict): The watch condition. The format is like:
  447. {
  448. "id": "tensor_too_large",
  449. "params": [
  450. {
  451. "name": "abs_mean_gt",
  452. "value": 1.1
  453. }
  454. ]
  455. }
  456. - id (str): Id of condition.
  457. - params (list[dict]): The list of param for this condition.
  458. - watch_nodes (list[str]): The list of node names.
  459. - watch_point_id (int): The id of watchpoint.
  460. - search_pattern (dict): The search pattern.
  461. - graph_name (str): The relative graph_name of the watched node.
  462. Returns:
  463. dict, the id of new watchpoint and metadata info.
  464. """
  465. watchpoint_opt = WatchpointOperator(self.cache_store, self.condition_mgr)
  466. return watchpoint_opt.create_watchpoint(params)
  467. def update_watchpoint(self, params):
  468. """
  469. Update watchpoint.
  470. Args:
  471. params (dict): Params for update watchpoint.
  472. - watch_point_id (int): The id of watchpoint.
  473. - watch_nodes (list[str]): The list of node names.
  474. - mode (int): The update operator on nodes. 0 for remove nodes from watch nodes.
  475. 1 for add nodes to watch nodes.
  476. - search_pattern (dict): The search pattern.
  477. - graph_name (str): The relative graph_name of the watched node.
  478. Returns:
  479. dict, the metadata info.
  480. """
  481. watchpoint_opt = WatchpointOperator(self.cache_store, self.condition_mgr)
  482. return watchpoint_opt.update_watchpoint(params)
  483. def delete_watchpoint(self, watch_point_id=None):
  484. """
  485. Delete watchpoint.
  486. Args:
  487. watch_point_id (Union[None, int]): The id of watchpoint.
  488. If None, delete all watchpoints. Default: None.
  489. Returns:
  490. dict, the metadata info.
  491. """
  492. watchpoint_opt = WatchpointOperator(self.cache_store, self.condition_mgr)
  493. return watchpoint_opt.delete_watchpoint(watch_point_id=watch_point_id)
  494. @try_except
  495. def control(self, params=None):
  496. """
  497. Control the training process.
  498. Args:
  499. params (dict): The control params.
  500. - mode (str): Acceptable control command, including `continue`,
  501. `pause` and `terminate`.
  502. - level (str): The control granularity, `node` level or `step` level.
  503. Default: `step`.
  504. - steps (int): Specify the steps that training should run.
  505. Used when `level` is `step`.
  506. - name (str): Specify the name of the node. Used when `level` is `node`.
  507. - graph_name (str): The graph name.
  508. Returns:
  509. dict, the response.
  510. """
  511. log.info("Receive control request: %s.", params)
  512. mode = params.pop('mode', None) if params else None
  513. training_controller = TrainingControlOperator(self.cache_store)
  514. training_controller.validate_mode(mode)
  515. return training_controller.control(mode, params)
  516. @try_except
  517. def recheck(self):
  518. """
  519. Recheck all watchpoints.
  520. Returns:
  521. dict, metadata info.
  522. """
  523. return TrainingControlOperator(self.cache_store).recheck()
  524. def retrieve_tensor_graph(self, tensor_name, graph_name, rank_id=0):
  525. """
  526. Retrieve tensor graph.
  527. Args:
  528. tensor_name (str): The tensor name from UI.
  529. graph_name (str): The graph name.
  530. rank_id (int): The id of rank. Default: 0.
  531. Returns:
  532. dict, tensor graph object.
  533. """
  534. if self.cache_store.get_stream_handler(Streams.METADATA).state != ServerStatus.WAITING.value:
  535. log.error("Failed to get tensor graph the MindSpore is not in waiting state.")
  536. raise DebuggerTensorGraphError
  537. log.info("Retrieve tensor graph for %s from %s", tensor_name, graph_name)
  538. tensor_graph_ops = TensorDetailInfo(self.cache_store).get_tensor_graph(tensor_name, graph_name, rank_id)
  539. return tensor_graph_ops
  540. def retrieve_tensor_hits(self, tensor_name, graph_name, rank_id=0):
  541. """
  542. Retrieve tensor hit information.
  543. Args:
  544. tensor_name (str): The tensor name from UI.
  545. graph_name (str): The graph name.
  546. rank_id (int): The id of rank. Default: 0.
  547. Returns:
  548. dict, tensor hit info.
  549. """
  550. if self.cache_store.get_stream_handler(Streams.METADATA).state != ServerStatus.WAITING.value:
  551. log.error("Failed to get tensor hits as the MindSpore is not in waiting state.")
  552. raise DebuggerTensorHitError
  553. log.info("Retrieve tensor hits for %s from %s", tensor_name, graph_name)
  554. watch_points = TensorDetailInfo(self.cache_store).get_tensor_watch_points(tensor_name, graph_name, rank_id)
  555. return {'watch_points': watch_points}
  556. def _hide_parameters_for_ui(self):
  557. """
  558. Hide some parameters on ui.
  559. Returns:
  560. dict, watch point list.
  561. """
  562. reply = self.cache_store.get_stream_handler(Streams.WATCHPOINT).get()
  563. watch_points = reply.get('watch_points')
  564. for i, watch_point in enumerate(watch_points):
  565. watch_condition = watch_point.get('watch_condition')
  566. parameters = watch_condition.get('params')
  567. watch_condition_id = watch_condition.get('id')
  568. mgr_condition = self.condition_mgr.get_condition(watch_condition_id)
  569. ui_watch_condition = []
  570. for param in parameters:
  571. parameter_definition = mgr_condition.get_parameter_definition(param['name'])
  572. if not parameter_definition.visible_on_ui:
  573. continue
  574. ui_watch_condition.append(param)
  575. reply['watch_points'][i]['watch_condition']['params'] = ui_watch_condition
  576. return reply