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

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