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_grpc_server.py 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 grpc server."""
  16. import copy
  17. from functools import wraps
  18. import mindinsight
  19. from mindinsight.debugger.common.log import LOGGER as log
  20. from mindinsight.debugger.common.utils import get_ack_reply, ServerStatus, \
  21. Streams, RunLevel
  22. from mindinsight.debugger.conditionmgr.condition import TargetTypeEnum, ParamNameEnum
  23. from mindinsight.debugger.proto import debug_grpc_pb2_grpc as grpc_server_base
  24. from mindinsight.debugger.proto.ms_graph_pb2 import GraphProto
  25. def debugger_wrap(func):
  26. """Wrapper for catch exception."""
  27. @wraps(func)
  28. def record_log(*args, **kwargs):
  29. try:
  30. return func(*args, **kwargs)
  31. except Exception as err:
  32. log.exception(err)
  33. raise err
  34. return record_log
  35. class DebuggerGrpcServer(grpc_server_base.EventListenerServicer):
  36. """The grpc server used to interactive with grpc client."""
  37. def __init__(self, cache_store, condition_mgr):
  38. """
  39. Initialize.
  40. Args:
  41. cache_store (DebuggerCache): Debugger cache store.
  42. """
  43. cache_store.initialize()
  44. self._cache_store = cache_store
  45. self._condition_mgr = condition_mgr
  46. # the next position of command queue to be queried
  47. self._pos = None
  48. # the status of grpc server, the value is in ServerStatus
  49. self._status = None
  50. # the run command cache, used to deal with left continue steps or nodes
  51. self._old_run_cmd = None
  52. # the view command cache, used to update tensor history through data queue
  53. self._received_view_cmd = None
  54. # the flag of receiving watch point hit
  55. self._received_hit = None
  56. self.init()
  57. def init(self):
  58. """Init debugger grpc server."""
  59. self._pos = '0'
  60. self._status = ServerStatus.PENDING
  61. self._old_run_cmd = {}
  62. self._received_view_cmd = {}
  63. self._received_hit = []
  64. self._cache_store.clean()
  65. @debugger_wrap
  66. def WaitCMD(self, request, context):
  67. """Wait for a command in DebuggerCache."""
  68. # check if graph have already received.
  69. log.info("Received WaitCMD at %s-th step.", request.cur_step)
  70. if self._status == ServerStatus.PENDING:
  71. log.warning("No graph received before WaitCMD.")
  72. reply = get_ack_reply(1)
  73. return reply
  74. # send graph if it has not been sent before
  75. self._pre_process(request)
  76. # deal with old command
  77. reply = self._deal_with_old_command()
  78. # wait for next command
  79. if reply is None:
  80. reply = self._wait_for_next_command()
  81. # check the reply
  82. if reply is None:
  83. reply = get_ack_reply(1)
  84. log.warning("Failed to get command event.")
  85. else:
  86. log.debug("Reply to WaitCMD: %s", reply)
  87. return reply
  88. def _pre_process(self, request):
  89. """Pre-process before dealing with command."""
  90. # check if version is mismatch, if mismatch, send mismatch info to UI
  91. if self._status == ServerStatus.MISMATCH:
  92. log.warning("Version of MindSpore and MindInsight are unmatched,"
  93. "waiting for user to terminate the script.")
  94. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  95. # put metadata into data queue
  96. metadata = metadata_stream.get(['state', 'debugger_version'])
  97. self._cache_store.put_data(metadata)
  98. return
  99. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  100. is_new_step = metadata_stream.step < request.cur_step
  101. is_new_node = metadata_stream.full_name != request.cur_node
  102. # clean cache data at the beginning of new step or node has been changed.
  103. if is_new_step or is_new_node:
  104. self._cache_store.clean_data()
  105. self._cache_store.get_stream_handler(Streams.TENSOR).clean_tensors(request.cur_step)
  106. if is_new_step:
  107. self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()
  108. # receive graph at the beginning of the training
  109. if self._status == ServerStatus.RECEIVE_GRAPH:
  110. self._send_graph_flag(metadata_stream)
  111. # receive new metadata
  112. if is_new_step or is_new_node:
  113. self._update_metadata(metadata_stream, request)
  114. self._send_received_tensor_tag()
  115. self._send_watchpoint_hit_flag()
  116. def _send_graph_flag(self, metadata_stream):
  117. """
  118. Send graph and metadata to UI.
  119. Args:
  120. metadata_stream (MetadataHandler): Metadata handler stream.
  121. """
  122. self._cache_store.clean_command()
  123. # receive graph in the beginning of the training
  124. self._status = ServerStatus.WAITING
  125. metadata_stream.state = ServerStatus.WAITING.value
  126. metadata = metadata_stream.get()
  127. res = self._cache_store.get_stream_handler(Streams.GRAPH).get()
  128. res.update(metadata)
  129. self._cache_store.put_data(res)
  130. log.debug("Put graph into data queue.")
  131. def _update_metadata(self, metadata_stream, metadata_proto):
  132. """
  133. Update metadata.
  134. Args:
  135. metadata_stream (MetadataHandler): Metadata handler stream.
  136. metadata_proto (MetadataProto): Metadata proto send by client.
  137. """
  138. # put new metadata into cache
  139. metadata_stream.put(metadata_proto)
  140. # update current node name and graph name
  141. graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)
  142. full_name = metadata_proto.cur_node
  143. graph_name = graph_stream.get_graph_id_by_full_name(
  144. full_name) if full_name else metadata_stream.graph_name
  145. cur_node = graph_stream.get_node_name_by_full_name(full_name, graph_name)
  146. metadata_stream.node_name = cur_node
  147. metadata_stream.graph_name = graph_name
  148. metadata = metadata_stream.get()
  149. self._cache_store.put_data(metadata)
  150. log.debug("Put new metadata into data queue.")
  151. def _send_received_tensor_tag(self):
  152. """Send received_finish_tag."""
  153. node_info = self._received_view_cmd.get('node_info')
  154. if not node_info or self._received_view_cmd.get('wait_for_tensor'):
  155. return
  156. metadata = self._cache_store.get_stream_handler(Streams.METADATA).get(['step', 'state'])
  157. ret = {'receive_tensor': node_info.copy()}
  158. ret.update(metadata)
  159. self._cache_store.put_data(ret)
  160. self._received_view_cmd.clear()
  161. log.debug("Send receive tensor flag for %s", node_info)
  162. def _send_watchpoint_hit_flag(self):
  163. """Send Watchpoint hit flag."""
  164. watchpoint_hit_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT)
  165. if not self._received_hit:
  166. return
  167. watchpoint_hits = self._received_hit
  168. self._received_hit = []
  169. for watchpoint_hit in watchpoint_hits:
  170. watchpoint_hit_stream.put(watchpoint_hit)
  171. watchpoint_hits_info = {'receive_watchpoint_hits': True}
  172. self._cache_store.put_data(watchpoint_hits_info)
  173. log.debug("Send the watchpoint hits to DataQueue.\nSend the reply.")
  174. def _deal_with_old_command(self):
  175. """Deal with old command."""
  176. event = None
  177. while self._cache_store.has_command(self._pos) and event is None:
  178. event = self._get_next_command()
  179. log.debug("Deal with old %s-th command:\n%s.", self._pos, event)
  180. # deal with continue run command
  181. if event is None and self._old_run_cmd:
  182. left_step_count = self._old_run_cmd.get('left_step_count')
  183. node_name = self._old_run_cmd.get('node_name')
  184. # node_name and left_step_count should not set at the same time
  185. if not (left_step_count or node_name) or (left_step_count and node_name):
  186. log.warning("Invalid old run command. %s", self._old_run_cmd)
  187. self._old_run_cmd.clear()
  188. return None
  189. if left_step_count:
  190. event = self._deal_with_left_continue_step(left_step_count)
  191. else:
  192. event = self._deal_with_left_continue_node(node_name)
  193. log.debug("Send old RunCMD.")
  194. return event
  195. def _deal_with_left_continue_step(self, left_step_count):
  196. """
  197. Construct run command with left continue step count.
  198. Args:
  199. left_step_count (int): The count of left steps to be executed.
  200. Returns:
  201. Event, the run command event.
  202. """
  203. event = get_ack_reply()
  204. event.run_cmd.run_steps = 1
  205. event.run_cmd.run_level = 'step'
  206. left_step_count = left_step_count - 1 if left_step_count > 0 else -1
  207. if not left_step_count:
  208. self._old_run_cmd.clear()
  209. else:
  210. self._old_run_cmd['left_step_count'] = left_step_count
  211. log.debug("Send old step RunCMD. Left step count: %s", left_step_count)
  212. return event
  213. def _deal_with_left_continue_node(self, node_name):
  214. """
  215. Construct run command with left continue nodes.
  216. Args:
  217. node_name (str): The target node name.
  218. Returns:
  219. Union[None, Event], the run command event.
  220. """
  221. cur_full_name = self._cache_store.get_stream_handler(Streams.METADATA).full_name
  222. if cur_full_name == node_name:
  223. log.info("Execute to target node: %s", node_name)
  224. self._old_run_cmd.clear()
  225. return None
  226. event = get_ack_reply()
  227. event.run_cmd.run_level = 'node'
  228. event.run_cmd.node_name = ''
  229. log.debug("Send old node RunCMD, cur node: %s, target node: %s", cur_full_name, node_name)
  230. return event
  231. def _wait_for_next_command(self):
  232. """
  233. Wait for next command.
  234. Returns:
  235. EventReply, the command event.
  236. """
  237. log.info("Start to wait for command.")
  238. if self._status != ServerStatus.MISMATCH:
  239. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  240. metadata_stream.state = ServerStatus.WAITING.value
  241. self._cache_store.put_data(metadata_stream.get())
  242. event = None
  243. while event is None and self._status not in [ServerStatus.RUNNING, ServerStatus.PENDING]:
  244. log.debug("Wait for %s-th command", self._pos)
  245. event = self._get_next_command()
  246. return event
  247. def _get_next_command(self):
  248. """Get next command."""
  249. self._pos, event = self._cache_store.get_command(self._pos)
  250. if event is None:
  251. return event
  252. # deal with command
  253. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  254. if isinstance(event, dict):
  255. event = self._deal_with_view_cmd(event)
  256. elif event.HasField('run_cmd'):
  257. event = self._deal_with_run_cmd(event)
  258. self._cache_store.put_data(metadata_stream.get())
  259. elif event.HasField('exit'):
  260. self._cache_store.clean()
  261. self._cache_store.put_data(metadata_stream.get())
  262. log.debug("Clean cache for exit cmd.")
  263. else:
  264. self._cache_store.get_stream_handler(Streams.WATCHPOINT).clean_cache_set_cmd(event.set_cmd)
  265. log.debug("get set cmd.")
  266. return event
  267. def _deal_with_view_cmd(self, event):
  268. """
  269. Deal with view cmd.
  270. Args:
  271. event (dict): View command params.
  272. - view_cmd (EventReply): EventReply with view command.
  273. - node_name (str): The center node name for view command.
  274. - tensor_name (str): The center tensor name for view command.
  275. - graph_name (str): The graph name of center node.
  276. Returns:
  277. EventReply, view command to be sent to client.
  278. """
  279. view_cmd = event.pop('view_cmd', None)
  280. log.debug("Receive view cmd for node: %s.", event)
  281. if not (view_cmd and event):
  282. log.debug("Invalid view command. Ignore it.")
  283. return None
  284. self._received_view_cmd['node_info'] = event
  285. self._received_view_cmd['wait_for_tensor'] = True
  286. return view_cmd
  287. def _deal_with_run_cmd(self, event):
  288. """Deal with run cmd."""
  289. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  290. run_cmd = event.run_cmd
  291. # receive step command
  292. if run_cmd.run_level == RunLevel.STEP.value:
  293. # receive pause cmd
  294. if not run_cmd.run_steps:
  295. log.debug("Pause training and wait for next command.")
  296. self._old_run_cmd.clear()
  297. # update metadata state from sending to waiting
  298. metadata_stream.state = ServerStatus.WAITING.value
  299. return None
  300. # receive step cmd
  301. left_steps = run_cmd.run_steps - 1
  302. event.run_cmd.run_steps = 1
  303. if left_steps:
  304. self._old_run_cmd['left_step_count'] = left_steps if left_steps > 0 else -1
  305. elif run_cmd.node_name:
  306. self._old_run_cmd['node_name'] = run_cmd.node_name
  307. run_cmd.node_name = ''
  308. # clean watchpoint hit cache
  309. if run_cmd.run_level == RunLevel.RECHECK.value:
  310. self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()
  311. log.debug("Receive RunCMD. Clean watchpoint hit cache.")
  312. # update metadata state from sending to running
  313. metadata_stream.state = ServerStatus.RUNNING.value
  314. return event
  315. @debugger_wrap
  316. def SendMetadata(self, request, context):
  317. """Send metadata into DebuggerCache."""
  318. log.info("Received Metadata.")
  319. if self._status != ServerStatus.PENDING:
  320. log.info("Re-initialize cache store when new session comes.")
  321. self.init()
  322. client_ip = context.peer().split(':', 1)[-1]
  323. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  324. reply = get_ack_reply()
  325. if request.training_done:
  326. log.info("The training from %s has finished.", client_ip)
  327. else:
  328. ms_version = request.ms_version
  329. if not ms_version:
  330. ms_version = '1.0.x'
  331. if version_match(ms_version, mindinsight.__version__) is False:
  332. log.info("Version is mismatched, mindspore is: %s, mindinsight is: %s",
  333. ms_version, mindinsight.__version__)
  334. self._status = ServerStatus.MISMATCH
  335. reply.version_matched = False
  336. metadata_stream.state = ServerStatus.MISMATCH.value
  337. else:
  338. log.info("version is matched.")
  339. reply.version_matched = True
  340. metadata_stream.debugger_version = {'ms': ms_version, 'mi': mindinsight.__version__}
  341. log.debug("Put ms_version from %s into cache.", client_ip)
  342. metadata_stream.put(request)
  343. metadata_stream.client_ip = client_ip
  344. log.debug("Put new metadata from %s into cache.", client_ip)
  345. # put metadata into data queue
  346. metadata = metadata_stream.get()
  347. self._cache_store.put_data(metadata)
  348. log.debug("Send the reply to %s.", client_ip)
  349. return reply
  350. @debugger_wrap
  351. def SendGraph(self, request_iterator, context):
  352. """Send graph into DebuggerCache."""
  353. log.info("Received graph.")
  354. reply = get_ack_reply()
  355. if self._status == ServerStatus.MISMATCH:
  356. log.info("Mindspore and Mindinsight is unmatched, waiting for user to terminate the service.")
  357. return reply
  358. serial_graph = b""
  359. for chunk in request_iterator:
  360. serial_graph += chunk.buffer
  361. graph = GraphProto.FromString(serial_graph)
  362. log.debug("Deserialize the graph %s. Receive %s nodes", graph.name, len(graph.node))
  363. graph_dict = {graph.name: graph}
  364. self._cache_store.get_stream_handler(Streams.GRAPH).put(graph_dict)
  365. self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(graph.const_vals)
  366. self._cache_store.get_stream_handler(Streams.METADATA).graph_name = graph.name
  367. self._record_parameter_names()
  368. self._status = ServerStatus.RECEIVE_GRAPH
  369. log.debug("Send the reply for graph.")
  370. return reply
  371. @debugger_wrap
  372. def SendMultiGraphs(self, request_iterator, context):
  373. """Send graph into DebuggerCache."""
  374. log.info("Received multi_graphs.")
  375. reply = get_ack_reply()
  376. if self._status == ServerStatus.MISMATCH:
  377. log.info("Mindspore and Mindinsight is unmatched, waiting for user to terminate the service.")
  378. return reply
  379. serial_graph = b""
  380. graph_dict = {}
  381. for chunk in request_iterator:
  382. serial_graph += chunk.buffer
  383. if chunk.finished:
  384. sub_graph = GraphProto.FromString(serial_graph)
  385. graph_dict[sub_graph.name] = sub_graph
  386. log.debug("Deserialize the graph %s. Receive %s nodes", sub_graph.name,
  387. len(sub_graph.node))
  388. serial_graph = b""
  389. self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(
  390. sub_graph.const_vals)
  391. self._cache_store.get_stream_handler(Streams.GRAPH).put(graph_dict)
  392. self._record_parameter_names()
  393. self._status = ServerStatus.RECEIVE_GRAPH
  394. log.debug("Send the reply for graph.")
  395. return reply
  396. def _record_parameter_names(self):
  397. """Record parameter full names in tensor handler."""
  398. parameter_nodes = self._cache_store.get_stream_handler(Streams.GRAPH).search_in_graph(
  399. pattern={'node_category': TargetTypeEnum.PARAMETER.value})
  400. tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)
  401. for node in parameter_nodes:
  402. tensor_name = [node.full_name + ':0']
  403. tensor_stream.record_parameter_names(tensor_name)
  404. @debugger_wrap
  405. def SendTensors(self, request_iterator, context):
  406. """Send tensors into DebuggerCache."""
  407. log.info("Received tensor.")
  408. tensor_contents = []
  409. tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)
  410. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  411. step = metadata_stream.step
  412. for tensor in request_iterator:
  413. tensor_contents.append(tensor.tensor_content)
  414. if tensor.finished:
  415. update_flag = tensor_stream.put(
  416. {'step': step, 'tensor_proto': tensor, 'tensor_contents': tensor_contents})
  417. if self._received_view_cmd.get('wait_for_tensor') and update_flag:
  418. # update_flag is used to avoid querying empty tensors again
  419. self._received_view_cmd['wait_for_tensor'] = False
  420. log.debug("Set wait for tensor flag to False.")
  421. tensor_contents = []
  422. continue
  423. reply = get_ack_reply()
  424. return reply
  425. @debugger_wrap
  426. def SendWatchpointHits(self, request_iterator, context):
  427. """Send watchpoint hits info DebuggerCache."""
  428. log.info("Received WatchpointHits. Left run cmd %s change to emtpy.", self._old_run_cmd)
  429. self._old_run_cmd.clear()
  430. if self._cache_store.get_stream_handler(Streams.METADATA).state == ServerStatus.RUNNING.value:
  431. # if the client session is running a script, all the cached command should be cleared
  432. # when received watchpoint_hits.
  433. self._cache_store.clean_command()
  434. # save the watchpoint_hits data
  435. watchpoint_hits = []
  436. watchpoint_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT)
  437. graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)
  438. for watchpoint_hit_proto in request_iterator:
  439. node_full_name = watchpoint_hit_proto.tensor.node_name
  440. graph_name = graph_stream.get_graph_id_by_full_name(node_full_name)
  441. if not graph_name:
  442. log.warning("Cannot find node %s in graph. Skip it.", node_full_name)
  443. continue
  444. ui_node_name = graph_stream.get_node_name_by_full_name(node_full_name, graph_name)
  445. log.debug("Receive watch point hit: %s", watchpoint_hit_proto)
  446. if not ui_node_name:
  447. log.info("Not support to show %s on graph.", node_full_name)
  448. continue
  449. watchpoint_hit = {
  450. 'tensor_proto': watchpoint_hit_proto.tensor,
  451. 'watchpoint': copy.deepcopy(watchpoint_stream.get_watchpoint_by_id(watchpoint_hit_proto.id)),
  452. 'node_name': ui_node_name,
  453. 'graph_name': graph_name
  454. }
  455. hit_params = {}
  456. for param in watchpoint_hit_proto.watch_condition.params:
  457. if param.name not in (ParamNameEnum.RTOL.value, ParamNameEnum.RANGE_START_INCLUSIVE.value,
  458. ParamNameEnum.RANGE_END_INCLUSIVE.value) \
  459. and watchpoint_hit_proto.error_code == 0:
  460. hit_params[param.name] = param.actual_value
  461. for i, param in enumerate(watchpoint_hit['watchpoint'].condition['params']):
  462. name = param['name']
  463. if name in hit_params.keys():
  464. watchpoint_hit['watchpoint'].condition['params'][i]['actual_value'] = hit_params[name]
  465. else:
  466. watchpoint_hit['watchpoint'].condition['params'][i]['actual_value'] = None
  467. watchpoint_hit['error_code'] = watchpoint_hit_proto.error_code
  468. watchpoint_hits.append(watchpoint_hit)
  469. self._received_hit = watchpoint_hits
  470. reply = get_ack_reply()
  471. return reply
  472. def version_match(mi_version, ms_version):
  473. """Judge if the version of Mindinsight and Mindspore is matched"""
  474. mi_major, mi_minor = mi_version.split('.')[:2]
  475. ms_major, ms_minor = ms_version.split('.')[:2]
  476. return mi_major == ms_major and mi_minor == ms_minor