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

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