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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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
  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):
  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._pos = None
  43. self._status = None
  44. self._continue_steps = None
  45. self._received_view_cmd = None
  46. self._received_hit = None
  47. self.init()
  48. def init(self):
  49. """Init debugger grpc server."""
  50. self._pos = '0'
  51. self._status = ServerStatus.PENDING
  52. self._continue_steps = 0
  53. self._received_view_cmd = {}
  54. self._received_hit = False
  55. self._cache_store.clean()
  56. @debugger_wrap
  57. def WaitCMD(self, request, context):
  58. """Wait for a command in DebuggerCache."""
  59. # check if graph have already received.
  60. log.info("Received WaitCMD at %s-th step.", request.cur_step)
  61. if self._status == ServerStatus.PENDING:
  62. log.warning("No graph received before WaitCMD.")
  63. reply = get_ack_reply(1)
  64. return reply
  65. # send graph if it has not been sent before
  66. self._pre_process(request)
  67. # deal with old command
  68. reply = self._deal_with_old_command()
  69. # wait for next command
  70. if reply is None:
  71. reply = self._wait_for_next_command()
  72. # check the reply
  73. if reply is None:
  74. reply = get_ack_reply(1)
  75. log.warning("Failed to get command event.")
  76. else:
  77. log.info("Reply to WaitCMD: %s", reply)
  78. return reply
  79. def _pre_process(self, request):
  80. """Pre-process before dealing with command."""
  81. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  82. is_new_step = metadata_stream.step < request.cur_step
  83. # clean cache data at the beginning of new step
  84. if is_new_step:
  85. self._cache_store.clean_data()
  86. self._cache_store.get_stream_handler(Streams.TENSOR).clean_tensors(request.cur_step)
  87. # receive graph at the beginning of the training
  88. if self._status == ServerStatus.RECEIVE_GRAPH:
  89. self._send_graph_flag(metadata_stream)
  90. # receive new metadata
  91. if is_new_step or metadata_stream.full_name != request.cur_node:
  92. self._update_metadata(metadata_stream, request)
  93. self._send_received_tensor_tag()
  94. self._send_watchpoint_hit_flag()
  95. def _send_graph_flag(self, metadata_stream):
  96. """
  97. Send graph and metadata to UI.
  98. Args:
  99. metadata_stream (MetadataHandler): Metadata handler stream.
  100. """
  101. self._cache_store.clean_command()
  102. # receive graph in the beginning of the training
  103. self._status = ServerStatus.WAITING
  104. metadata_stream.state = 'waiting'
  105. metadata = metadata_stream.get()
  106. res = self._cache_store.get_stream_handler(Streams.GRAPH).get()
  107. res.update(metadata)
  108. self._cache_store.put_data(res)
  109. log.debug("Put graph into data queue.")
  110. def _update_metadata(self, metadata_stream, metadata_proto):
  111. """
  112. Update metadata.
  113. Args:
  114. metadata_stream (MetadataHandler): Metadata handler stream.
  115. metadata_proto (MetadataProto): Metadata proto send by client.
  116. """
  117. # put new metadata into cache
  118. metadata_stream.put(metadata_proto)
  119. cur_node = self._cache_store.get_stream_handler(Streams.GRAPH).get_node_name_by_full_name(
  120. metadata_proto.cur_node) if metadata_proto.cur_node else ''
  121. metadata_stream.node_name = cur_node
  122. metadata = metadata_stream.get()
  123. self._cache_store.put_data(metadata)
  124. log.debug("Put new metadata into data queue.")
  125. def _send_received_tensor_tag(self):
  126. """Send received_finish_tag."""
  127. node_name = self._received_view_cmd.get('node_name')
  128. if not node_name or self._received_view_cmd.get('wait_for_tensor'):
  129. return
  130. metadata = self._cache_store.get_stream_handler(Streams.METADATA).get()
  131. ret = {'receive_tensor': {'node_name': node_name}}
  132. ret.update(metadata)
  133. self._cache_store.put_data(ret)
  134. self._received_view_cmd.clear()
  135. log.debug("Send receive tensor flag for %s", node_name)
  136. def _send_watchpoint_hit_flag(self):
  137. """Send Watchpoint hit flag."""
  138. watchpoint_hit_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT)
  139. if watchpoint_hit_stream.empty or not self._received_hit:
  140. return
  141. self._received_hit = False
  142. watchpoint_hits_info = watchpoint_hit_stream.get()
  143. self._cache_store.put_data(watchpoint_hits_info)
  144. log.debug("Send the watchpoint hits to DataQueue.\nSend the reply.")
  145. def _deal_with_old_command(self):
  146. """Deal with old command."""
  147. event = None
  148. while self._cache_store.has_command(self._pos) and event is None:
  149. event = self._get_next_command()
  150. log.debug("Deal with old %s-th command:\n%s.", self._pos, event)
  151. # continue multiple steps training
  152. if event is None and self._continue_steps:
  153. event = get_ack_reply()
  154. event.run_cmd.run_steps = 1
  155. event.run_cmd.run_level = 'step'
  156. self._continue_steps = self._continue_steps - 1 if self._continue_steps > 0 else -1
  157. self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()
  158. log.debug("Send RunCMD. Clean watchpoint hit.")
  159. return event
  160. def _wait_for_next_command(self):
  161. """
  162. Wait for next command.
  163. Returns:
  164. EventReply, the command event.
  165. """
  166. log.info("Start to wait for command.")
  167. self._cache_store.get_stream_handler(Streams.METADATA).state = 'waiting'
  168. self._cache_store.put_data({'metadata': {'state': 'waiting'}})
  169. event = None
  170. while event is None and self._status == ServerStatus.WAITING:
  171. log.debug("Wait for %s-th command", self._pos)
  172. event = self._get_next_command()
  173. return event
  174. def _get_next_command(self):
  175. """Get next command."""
  176. self._pos, event = self._cache_store.get_command(self._pos)
  177. if event is None:
  178. return event
  179. if isinstance(event, dict):
  180. event = self._deal_with_view_cmd(event)
  181. elif event.HasField('run_cmd'):
  182. event = self._deal_with_run_cmd(event)
  183. elif event.HasField('exit'):
  184. self._cache_store.clean()
  185. log.info("Clean cache for exit cmd.")
  186. return event
  187. def _deal_with_view_cmd(self, event):
  188. """Deal with view cmd."""
  189. view_cmd = event.get('view_cmd')
  190. node_name = event.get('node_name')
  191. log.debug("Receive view cmd for node: %s.", node_name)
  192. if not (view_cmd and node_name):
  193. log.debug("Invalid view command. Ignore it.")
  194. return None
  195. self._received_view_cmd['node_name'] = node_name
  196. self._received_view_cmd['wait_for_tensor'] = True
  197. return view_cmd
  198. def _deal_with_run_cmd(self, event):
  199. """Deal with run cmd."""
  200. run_cmd = event.run_cmd
  201. # receive step command
  202. if run_cmd.run_level == 'step':
  203. # receive pause cmd
  204. if run_cmd.run_steps == 0:
  205. log.debug("Pause training and wait for next command.")
  206. self._continue_steps = 0
  207. return None
  208. # receive step cmd
  209. self._continue_steps = run_cmd.run_steps - 1
  210. event.run_cmd.run_steps = 1
  211. self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()
  212. log.debug("Receive RunCMD. Clean watchpoint hit cache.")
  213. return event
  214. @debugger_wrap
  215. def SendMetadata(self, request, context):
  216. """Send metadata into DebuggerCache."""
  217. log.info("Received Metadata.")
  218. if self._status != ServerStatus.PENDING:
  219. log.info("Re-initialize cache store when new session comes.")
  220. self.init()
  221. client_ip = context.peer().split(':', 1)[-1]
  222. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  223. if request.training_done:
  224. log.info("The training from %s has finished.", client_ip)
  225. else:
  226. metadata_stream.put(request)
  227. metadata_stream.client_ip = client_ip
  228. log.debug("Put new metadata from %s into cache.", client_ip)
  229. # put metadata into data queue
  230. metadata = metadata_stream.get()
  231. self._cache_store.put_data(metadata)
  232. reply = get_ack_reply()
  233. log.debug("Send the reply to %s.", client_ip)
  234. return reply
  235. @debugger_wrap
  236. def SendGraph(self, request_iterator, context):
  237. """Send graph into DebuggerCache."""
  238. log.info("Received graph.")
  239. serial_graph = b""
  240. for chunk in request_iterator:
  241. serial_graph += chunk.buffer
  242. graph = GraphProto.FromString(serial_graph)
  243. log.debug("Deserialize the graph. Receive %s nodes", len(graph.node))
  244. self._cache_store.get_stream_handler(Streams.GRAPH).put(graph)
  245. self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(graph.const_vals)
  246. self._status = ServerStatus.RECEIVE_GRAPH
  247. reply = get_ack_reply()
  248. log.debug("Send the reply for graph.")
  249. return reply
  250. @debugger_wrap
  251. def SendTensors(self, request_iterator, context):
  252. """Send tensors into DebuggerCache."""
  253. log.info("Received tensor.")
  254. tensor_construct = []
  255. tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)
  256. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  257. tensor_names = []
  258. step = metadata_stream.step
  259. for tensor in request_iterator:
  260. tensor_construct.append(tensor)
  261. if tensor.finished:
  262. update_flag = tensor_stream.put({'step': step, 'tensor_protos': tensor_construct})
  263. if self._received_view_cmd.get('wait_for_tensor') and update_flag:
  264. self._received_view_cmd['wait_for_tensor'] = False
  265. log.debug("Set wait for tensor flag to False.")
  266. tensor_construct = []
  267. tensor_names.append(':'.join([tensor.node_name, tensor.slot]))
  268. continue
  269. reply = get_ack_reply()
  270. return reply
  271. @debugger_wrap
  272. def SendWatchpointHits(self, request_iterator, context):
  273. """Send watchpoint hits info DebuggerCache."""
  274. log.info("Received WatchpointHits. Left steps %d change to 0.", self._continue_steps)
  275. self._continue_steps = 0
  276. self._received_hit = True
  277. watchpoint_hit_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT)
  278. watchpoint_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT)
  279. graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)
  280. for watchpoint_hit_proto in request_iterator:
  281. ui_node_name = graph_stream.get_node_name_by_full_name(
  282. watchpoint_hit_proto.tensor.node_name)
  283. log.debug("Receive watch point hit: %s", watchpoint_hit_proto)
  284. if not ui_node_name:
  285. log.info("Not support to show %s on graph.", watchpoint_hit_proto.tensor.node_name)
  286. continue
  287. watchpoint_hit = {
  288. 'tensor_proto': watchpoint_hit_proto.tensor,
  289. 'watchpoint': watchpoint_stream.get_watchpoint_by_id(watchpoint_hit_proto.id),
  290. 'node_name': ui_node_name
  291. }
  292. watchpoint_hit_stream.put(watchpoint_hit)
  293. reply = get_ack_reply()
  294. return reply