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

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