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 19 kB

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